From 124fc2557e4dd02cbe2a1ce316baafb2011f2389 Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Fri, 23 Oct 2026 18:03:52 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=8E=20Atmosphere=20explore=20tab=20(#1?= =?UTF-8?q?2188)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: DS Boyce <260543580+ds-boyce@users.noreply.github.com> --- .oxlintrc.json | 1 + lexicons.json | 9 +- lexicons/README.md | 19 + lexicons/app/bsky/embed/external.json | 335 ++++++++ .../app/bsky/embed/getEmbedExternalView.json | 45 +- .../unspecced/getAtmosphereExploreTab.json | 180 +++++ src/analytics/features/types.ts | 2 +- src/analytics/metrics/types.ts | 3 + src/components/Button.tsx | 1 + src/components/Gallery/README.md | 25 +- src/components/Gallery/Storybook.tsx | 83 ++ .../Gallery/__tests__/Gallery.test.tsx | 105 ++- src/components/Gallery/index.tsx | 21 +- src/components/Link.tsx | 5 + .../Post/Embed/StandardSiteEmbed/index.tsx | 37 +- src/screens/Atmosphere/ActivityTab.tsx | 45 ++ src/screens/Atmosphere/ExploreTab.tsx | 83 ++ .../Atmosphere/__tests__/ExploreTab.test.tsx | 271 +++++++ .../__tests__/fixtures/exploreResponse.ts | 102 +++ .../__tests__/fixtures/livestreamPreview.ts | 62 ++ .../components/AnnouncementBanner.tsx | 80 ++ src/screens/Atmosphere/components/AppCard.tsx | 85 +++ .../Atmosphere/components/ArticleCard.tsx | 122 +++ .../Atmosphere/components/AtmosphereNux.tsx | 89 +++ .../Atmosphere/components/ExploreGallery.tsx | 47 ++ .../components/ExploreSectionHeader.tsx | 10 + .../Atmosphere/components/FeaturedApps.tsx | 24 + .../components/FeaturedArticles.tsx | 38 + .../components/FeaturedLivestreams.tsx | 38 + .../Atmosphere/components/FeaturedPhotos.tsx | 32 + .../components/FeaturedPublications.tsx | 38 + .../Atmosphere/components/LivestreamCard.tsx | 194 +++++ .../Atmosphere/components/PhotoCard.tsx | 132 ++++ .../Atmosphere/components/PublicationCard.tsx | 50 ++ .../__tests__/ExploreGallery.test.tsx | 204 +++++ .../__tests__/ExploreSectionHeader.test.tsx | 20 + .../__tests__/FeaturedSections.test.tsx | 249 ++++++ .../__tests__/PublicationCard.test.tsx | 251 ++++++ .../__tests__/galleryFocus.test.tsx | 246 ++++++ .../data/__tests__/exploreData.test.ts | 715 ++++++++++++++++++ .../useAtmosphereExploreQuery.test.tsx | 221 ++++++ src/screens/Atmosphere/data/exploreData.ts | 256 +++++++ .../data/useAtmosphereExploreQuery.ts | 30 + .../{Atmosphere.tsx => Atmosphere/index.tsx} | 27 +- src/state/queries/nuxs/definitions.ts | 6 + src/view/shell/Drawer.tsx | 2 +- src/view/shell/desktop/LeftNav.tsx | 2 +- 47 files changed, 4588 insertions(+), 54 deletions(-) create mode 100644 lexicons/README.md create mode 100644 lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json create mode 100644 src/screens/Atmosphere/ActivityTab.tsx create mode 100644 src/screens/Atmosphere/ExploreTab.tsx create mode 100644 src/screens/Atmosphere/__tests__/ExploreTab.test.tsx create mode 100644 src/screens/Atmosphere/__tests__/fixtures/exploreResponse.ts create mode 100644 src/screens/Atmosphere/__tests__/fixtures/livestreamPreview.ts create mode 100644 src/screens/Atmosphere/components/AnnouncementBanner.tsx create mode 100644 src/screens/Atmosphere/components/AppCard.tsx create mode 100644 src/screens/Atmosphere/components/ArticleCard.tsx create mode 100644 src/screens/Atmosphere/components/AtmosphereNux.tsx create mode 100644 src/screens/Atmosphere/components/ExploreGallery.tsx create mode 100644 src/screens/Atmosphere/components/ExploreSectionHeader.tsx create mode 100644 src/screens/Atmosphere/components/FeaturedApps.tsx create mode 100644 src/screens/Atmosphere/components/FeaturedArticles.tsx create mode 100644 src/screens/Atmosphere/components/FeaturedLivestreams.tsx create mode 100644 src/screens/Atmosphere/components/FeaturedPhotos.tsx create mode 100644 src/screens/Atmosphere/components/FeaturedPublications.tsx create mode 100644 src/screens/Atmosphere/components/LivestreamCard.tsx create mode 100644 src/screens/Atmosphere/components/PhotoCard.tsx create mode 100644 src/screens/Atmosphere/components/PublicationCard.tsx create mode 100644 src/screens/Atmosphere/components/__tests__/ExploreGallery.test.tsx create mode 100644 src/screens/Atmosphere/components/__tests__/ExploreSectionHeader.test.tsx create mode 100644 src/screens/Atmosphere/components/__tests__/FeaturedSections.test.tsx create mode 100644 src/screens/Atmosphere/components/__tests__/PublicationCard.test.tsx create mode 100644 src/screens/Atmosphere/components/__tests__/galleryFocus.test.tsx create mode 100644 src/screens/Atmosphere/data/__tests__/exploreData.test.ts create mode 100644 src/screens/Atmosphere/data/__tests__/useAtmosphereExploreQuery.test.tsx create mode 100644 src/screens/Atmosphere/data/exploreData.ts create mode 100644 src/screens/Atmosphere/data/useAtmosphereExploreQuery.ts rename src/screens/{Atmosphere.tsx => Atmosphere/index.tsx} (66%) diff --git a/.oxlintrc.json b/.oxlintrc.json index 255634394..d05dcca6b 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -394,6 +394,7 @@ "excludeFiles": [ "src/components/Gallery/**", "src/components/images/Gallery/**", + "src/screens/Atmosphere/components/ExploreGallery.tsx", "src/view/screens/Storybook/Storybook.tsx" ], "rules": { diff --git a/lexicons.json b/lexicons.json index 458e49151..c0b5c9323 100644 --- a/lexicons.json +++ b/lexicons.json @@ -118,6 +118,7 @@ "app.bsky.notification.unregisterPush", "app.bsky.notification.updateSeen", "app.bsky.richtext.facet", + "app.bsky.unspecced.getAtmosphereExploreTab", "app.bsky.video.defs", "app.bsky.video.getJobStatus", "app.bsky.video.getUploadLimits", @@ -422,7 +423,7 @@ }, "app.bsky.embed.external": { "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.embed.external", - "cid": "bafyreigwach36azu4xg3jvcmb6fe53umfln3wkuj5srqsvcjaypa6rw534" + "cid": "bafyreidhctlel6ogjn5tamcdtuviu7rtdezt6ern7pkubpcin2actwxbym" }, "app.bsky.embed.gallery": { "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.embed.gallery", @@ -430,7 +431,7 @@ }, "app.bsky.embed.getEmbedExternalView": { "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.embed.getEmbedExternalView", - "cid": "bafyreicnv2umobvrfrlo6tqw7umcsxv77owcwit3vld7l46fphpy5uuzky" + "cid": "bafyreicy4fjqex6gezxnqgc7k3y6qg2ghsxmwr3ugm3bifdthukn7d7lvm" }, "app.bsky.embed.images": { "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.embed.images", @@ -752,6 +753,10 @@ "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.richtext.facet", "cid": "bafyreidg56eo7zynf6ihz4xb627vwoqf5idnevkmwp7sxc4tijg6xngbu4" }, + "app.bsky.unspecced.getAtmosphereExploreTab": { + "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.unspecced.getAtmosphereExploreTab", + "cid": "bafyreiez66qb7byto44nzivpn27ykzdgilgpuqogeusypl3mln7wicjnry" + }, "app.bsky.video.defs": { "uri": "at://did:plc:4v4y5r3lwsbtmsxhile2ljac/com.atproto.lexicon.schema/app.bsky.video.defs", "cid": "bafyreicorzkcw5zp4zjsiepyakpfn3vvtpwsbqwzsy43d2y6i3t5rp3meu" diff --git a/lexicons/README.md b/lexicons/README.md new file mode 100644 index 000000000..ac557b969 --- /dev/null +++ b/lexicons/README.md @@ -0,0 +1,19 @@ +# Lexicons + +Published schemas are fetched with `pnpm lexicons:update`; use a scoped manifest +to exclude the unpublished exception below. `lexicons.json` pins each schema's +URI and CID, and `pnpm lexicons:verify` checks the installed files against it. +Do not hand-edit published schemas. + +## Exception: `app.bsky.unspecced.getAtmosphereExploreTab` + +The `app.bsky.unspecced` namespace is intentionally unpublished (it is a DNS +carveout upstream, and resolving it is a CI violation there), so the installer +cannot fetch it. Its schema is copied from the merged upstream source, +[`lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json` at `293d6494ed90`](https://github.com/bluesky-social/bsky/blob/293d6494ed9058e28a04b97133d16ab8abe7ef5e/lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json). + +In `lexicons.json`, its `cid` is a locally calculated content-integrity pin, not +a published record CID, and its `uri` is only an installer compatibility hint, +not a published record location. An unscoped network update will fail when it +tries to fetch this schema. Update it from upstream JSON and compute its local +CID with `cidForLex` from `@atproto/lex-cbor`. diff --git a/lexicons/app/bsky/embed/external.json b/lexicons/app/bsky/embed/external.json index d4bd88649..d7db938bc 100644 --- a/lexicons/app/bsky/embed/external.json +++ b/lexicons/app/bsky/embed/external.json @@ -87,6 +87,153 @@ } } }, + "viewArticle": { + "type": "object", + "required": [ + "uri", + "title", + "description" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "image": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "labels": { + "type": "array", + "items": { + "ref": "com.atproto.label.defs#label", + "type": "ref" + } + }, + "likers": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + }, + "maxLength": 3, + "description": "Available profile previews. Selected deterministically by DID; not a ranking." + }, + "createdAt": { + "type": "string", + "format": "datetime" + }, + "likeCount": { + "type": "integer", + "minimum": 0 + }, + "publisher": { + "ref": "#viewArticlePublication", + "type": "ref" + }, + "updatedAt": { + "type": "string", + "format": "datetime" + }, + "description": { + "type": "string" + }, + "readingTime": { + "type": "integer", + "minimum": 1 + }, + "associatedRefs": { + "type": "array", + "items": { + "ref": "com.atproto.repo.strongRef", + "type": "ref" + } + }, + "associatedProfiles": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + } + } + } + }, + "viewGallery": { + "type": "object", + "required": [ + "uri", + "title", + "description", + "items" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "items": { + "type": "array", + "items": { + "refs": [ + "#viewGalleryImage" + ], + "type": "union" + }, + "description": "The media items in the gallery. Each item may be of a different type, but all types must be supported by the client." + }, + "title": { + "type": "string" + }, + "labels": { + "type": "array", + "items": { + "ref": "com.atproto.label.defs#label", + "type": "ref" + } + }, + "likers": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + }, + "maxLength": 3, + "description": "Available profile previews. Selected deterministically by DID; not a ranking." + }, + "createdAt": { + "type": "string", + "format": "datetime" + }, + "likeCount": { + "type": "integer", + "minimum": 0 + }, + "updatedAt": { + "type": "string", + "format": "datetime" + }, + "description": { + "type": "string" + }, + "associatedRefs": { + "type": "array", + "items": { + "ref": "com.atproto.repo.strongRef", + "type": "ref" + } + }, + "associatedProfiles": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + } + } + } + }, "viewExternal": { "type": "object", "required": [ @@ -152,6 +299,99 @@ } } }, + "viewLivestream": { + "type": "object", + "required": [ + "uri", + "title", + "description", + "active" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "image": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "active": { + "type": "boolean", + "description": "True if the livestream is currently active at the time this view is served, false if it has ended." + }, + "labels": { + "type": "array", + "items": { + "ref": "com.atproto.label.defs#label", + "type": "ref" + } + }, + "endedAt": { + "type": "string", + "format": "datetime" + }, + "createdAt": { + "type": "string", + "format": "datetime" + }, + "startedAt": { + "type": "string", + "format": "datetime" + }, + "updatedAt": { + "type": "string", + "format": "datetime" + }, + "description": { + "type": "string" + }, + "associatedRefs": { + "type": "array", + "items": { + "ref": "com.atproto.repo.strongRef", + "type": "ref" + } + }, + "associatedProfiles": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + } + } + } + }, + "viewGalleryImage": { + "type": "object", + "required": [ + "thumbnail", + "fullsize" + ], + "properties": { + "alt": { + "type": "string", + "description": "Alt text description of the image, for accessibility." + }, + "fullsize": { + "type": "string", + "format": "uri", + "description": "Fully-qualified URL where a large version of the image can be fetched. May or may not be the exact original blob. For example, CDN location provided by the App View." + }, + "thumbnail": { + "type": "string", + "format": "uri", + "description": "Fully-qualified URL where a thumbnail of the image can be fetched. For example, CDN location provided by the App View." + }, + "aspectRatio": { + "ref": "app.bsky.embed.defs#aspectRatio", + "type": "ref" + } + } + }, "viewExternalSource": { "type": "object", "required": [ @@ -182,6 +422,80 @@ }, "description": "The source of an external embed, such as a standard.site publication." }, + "viewArticlePublication": { + "type": "object", + "required": [ + "uri", + "title", + "description" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "logo": { + "type": "string", + "format": "uri" + }, + "image": { + "type": "string", + "format": "uri" + }, + "theme": { + "ref": "#viewArticlePublicationTheme", + "type": "ref" + }, + "title": { + "type": "string" + }, + "labels": { + "type": "array", + "items": { + "ref": "com.atproto.label.defs#label", + "type": "ref" + } + }, + "createdAt": { + "type": "string", + "format": "datetime" + }, + "updatedAt": { + "type": "string", + "format": "datetime" + }, + "description": { + "type": "string" + }, + "subscribers": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + }, + "maxLength": 3, + "description": "Available profile previews. Selected deterministically by DID; not a ranking." + }, + "associatedRefs": { + "type": "array", + "items": { + "ref": "com.atproto.repo.strongRef", + "type": "ref" + } + }, + "subscriptionCount": { + "type": "integer", + "minimum": 0 + }, + "associatedProfiles": { + "type": "array", + "items": { + "ref": "app.bsky.actor.defs#profileViewBasic", + "type": "ref" + } + } + } + }, "viewExternalSourceTheme": { "type": "object", "properties": { @@ -203,6 +517,27 @@ } }, "description": "The theme colors of an external source, such as a site.standard.publication. These colors may be used when rendering an embed from that source." + }, + "viewArticlePublicationTheme": { + "type": "object", + "properties": { + "accent": { + "type": "string", + "description": "Hex color string, if available. Example: '#ffffff'." + }, + "background": { + "type": "string", + "description": "Hex color string, if available. Example: '#ffffff'." + }, + "foreground": { + "type": "string", + "description": "Hex color string, if available. Example: '#ffffff'." + }, + "accentForeground": { + "type": "string", + "description": "Hex color string, if available. Example: '#ffffff'." + } + } } }, "$type": "com.atproto.lexicon.schema", diff --git a/lexicons/app/bsky/embed/getEmbedExternalView.json b/lexicons/app/bsky/embed/getEmbedExternalView.json index 7b60eb3fc..ec5eb09a5 100644 --- a/lexicons/app/bsky/embed/getEmbedExternalView.json +++ b/lexicons/app/bsky/embed/getEmbedExternalView.json @@ -7,10 +7,20 @@ "schema": { "type": "object", "properties": { + "data": { + "refs": [ + "app.bsky.embed.external#viewArticle", + "app.bsky.embed.external#viewArticlePublication", + "app.bsky.embed.external#viewGallery", + "app.bsky.embed.external#viewLivestream" + ], + "type": "union", + "description": "Preferred to #view. Hydrated data of the embed. Present only when validation passed and the records supply enough information to populate the required fields." + }, "view": { "ref": "app.bsky.embed.external#view", "type": "ref", - "description": "Hydrated view of the embed. Present only when the resolved records back the requested URL and supply enough information to populate the required `viewExternal` fields. Omitted alongside the rest of the response when no records resolved or validation failed." + "description": "Legacy hydrated view of the embed, returned for Standard.site records only. Present only when validation passed and the records supply enough information to populate the required `viewExternal` fields." }, "associatedRefs": { "type": "array", @@ -18,13 +28,28 @@ "ref": "com.atproto.repo.strongRef", "type": "ref" }, - "description": "StrongRefs (URI+CID) of the Atmosphere records that backed this view, suitable for embedding into a post's external.associatedRefs." + "description": "StrongRefs (URI+CID) of the Atmosphere records selected for persistence in a post, suitable for embedding into its external.associatedRefs: the canonical record, plus only the additional records the service chooses to persist for its collection. This can be a subset of the records used to render `data`, which may also draw on other hydrated records such as recommendations, subscriptions, or favorites. Present only when validation passed. Index-aligned with `associatedRecords`." }, "associatedRecords": { "type": "array", "items": { "type": "unknown", - "description": "The raw record data of the Atmosphere records that backed this view. This is returned for convenience, to avoid the need for the client to separately fetch the record data for the associatedRefs. Example: the site.standard.document and site.standard.publication records that backed this view." + "description": "The raw record data of the Atmosphere records selected for persistence, index-aligned with `associatedRefs`. Returned for convenience, to avoid the client separately fetching them. Present only when validation passed." + } + }, + "unverifiedAssociatedRefs": { + "type": "array", + "items": { + "ref": "com.atproto.repo.strongRef", + "type": "ref" + }, + "description": "StrongRefs (URI+CID) of the same persistence-selected Atmosphere records (the canonical record plus chosen additional records) when validation of the requested `url` failed. These must not be written to a post. Index-aligned with `unverifiedAssociatedRecords`." + }, + "unverifiedAssociatedRecords": { + "type": "array", + "items": { + "type": "unknown", + "description": "The raw record data of the persistence-selected Atmosphere records, index-aligned with `unverifiedAssociatedRefs`. Present only when validation failed." } } } @@ -34,14 +59,13 @@ "parameters": { "type": "params", "required": [ - "url", - "uris" + "url" ], "properties": { "url": { "type": "string", "format": "uri", - "description": "The canonical web URL the embed represents (typically the URL the user pasted into the composer). Used as the returned view's `uri`. May be used for validation in the future." + "description": "The canonical web URL the embed represents (typically the URL the user pasted into the composer). Used as the returned view's `uri`, and validated against the resolved records." }, "uris": { "type": "array", @@ -50,11 +74,16 @@ "format": "at-uri" }, "maxLength": 4, - "description": "AT-URIs of any Atmosphere records that can be resolved and used to construct #externalView views. Example: a site.standard.document and optionally its associated site.standard.publication." + "description": "Legacy input for Standard.site callers, ignored when `canonicalUri` is provided. A single record is selected from it: the first site.standard.document URI, otherwise the first site.standard.publication URI. Other entries are ignored; a document's publication is discovered from the document itself." + }, + "canonicalUri": { + "type": "string", + "format": "at-uri", + "description": "The canonical AT URI of the atproto record found on the webpage. When provided, takes precedence over `uris`, which is then ignored." } } }, - "description": "Resolve one or more AT-URIs into the data needed to render an enhanced external embed. Returns `associatedRefs` (strongRefs to embed into a post's external.associatedRefs), the raw `associatedRecords`, and a hydrated `view`. The response is empty (`{}`) when no records were resolvable, or when validation determined the resolved records don't actually back the requested URL; clients should fall back to their own link-card rendering in that case and skip writing strongRefs to the post." + "description": "Resolve one AT-URI record into the data needed to render an enhanced external embed. The records are validated against the requested `url` before any view is built. When validation passes, returns `data`, `associatedRefs` (strongRefs to embed into a post's external.associatedRefs) and the raw `associatedRecords`, plus a legacy `view` for Standard.site records only. When validation fails, only `unverifiedAssociatedRefs` and `unverifiedAssociatedRecords` are returned and no view or data is built. The response is empty (`{}`) when no record URI was usable or the record could not be resolved; clients should fall back to their own link-card rendering in that case and skip writing strongRefs to the post." } }, "$type": "com.atproto.lexicon.schema", diff --git a/lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json b/lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json new file mode 100644 index 000000000..0ca19de08 --- /dev/null +++ b/lexicons/app/bsky/unspecced/getAtmosphereExploreTab.json @@ -0,0 +1,180 @@ +{ + "lexicon": 1, + "id": "app.bsky.unspecced.getAtmosphereExploreTab", + "defs": { + "main": { + "type": "query", + "description": "Get Atmosphere Explore content. Articles are recommended when algorithmic recommendations are enabled for the request, and curated otherwise; other sections are curated. Authentication is optional; authenticated requests include viewer-specific profile state.", + "parameters": { + "type": "params", + "properties": { + "langs": { + "type": "array", + "description": "Preferred languages for article recommendations when algorithmic recommendations are enabled. Ignored otherwise.", + "items": { "type": "string", "format": "language" } + }, + "countryCode": { + "type": "string", + "description": "The ISO 3166-1 alpha-2 country code used to select curated content." + }, + "regionCode": { + "type": "string", + "description": "The ISO 3166-2 region code used to select curated content." + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": [ + "articles", + "publications", + "photos", + "livestreams", + "apps" + ], + "properties": { + "announcementBanner": { + "type": "ref", + "ref": "#announcementBanner" + }, + "articles": { "type": "ref", "ref": "#articleList" }, + "publications": { "type": "ref", "ref": "#publicationList" }, + "photos": { "type": "ref", "ref": "#galleryList" }, + "livestreams": { "type": "ref", "ref": "#livestreamList" }, + "apps": { + "type": "array", + "maxLength": 100, + "items": { "type": "ref", "ref": "#appCard" } + } + } + } + } + }, + "articleList": { + "type": "object", + "required": ["items"], + "properties": { + "items": { + "type": "array", + "items": { "type": "ref", "ref": "#articleItem" } + }, + "recIdStr": { + "type": "string", + "description": "Snowflake for this list's recommendation, use when submitting recommendation events. Omitted when the list is not algorithmically recommended." + } + } + }, + "publicationList": { + "type": "object", + "required": ["items"], + "properties": { + "items": { + "type": "array", + "items": { "type": "ref", "ref": "#publicationItem" } + }, + "recIdStr": { + "type": "string", + "description": "Snowflake for this list's recommendation, use when submitting recommendation events. Omitted when the list is not algorithmically recommended." + } + } + }, + "galleryList": { + "type": "object", + "required": ["items"], + "properties": { + "items": { + "type": "array", + "items": { "type": "ref", "ref": "#galleryItem" } + }, + "recIdStr": { + "type": "string", + "description": "Snowflake for this list's recommendation, use when submitting recommendation events. Omitted when the list is not algorithmically recommended." + } + } + }, + "livestreamList": { + "type": "object", + "required": ["items"], + "properties": { + "items": { + "type": "array", + "items": { "type": "ref", "ref": "#livestreamItem" } + }, + "recIdStr": { + "type": "string", + "description": "Snowflake for this list's recommendation, use when submitting recommendation events. Omitted when the list is not algorithmically recommended." + } + } + }, + "articleItem": { + "type": "object", + "required": ["featured", "view"], + "properties": { + "featured": { "type": "boolean" }, + "view": { "type": "ref", "ref": "app.bsky.embed.external#viewArticle" } + } + }, + "publicationItem": { + "type": "object", + "required": ["featured", "view"], + "properties": { + "featured": { "type": "boolean" }, + "view": { + "type": "ref", + "ref": "app.bsky.embed.external#viewArticlePublication" + } + } + }, + "galleryItem": { + "type": "object", + "required": ["featured", "view"], + "properties": { + "featured": { "type": "boolean" }, + "view": { "type": "ref", "ref": "app.bsky.embed.external#viewGallery" } + } + }, + "livestreamItem": { + "type": "object", + "required": ["featured", "view"], + "properties": { + "featured": { "type": "boolean" }, + "view": { + "type": "ref", + "ref": "app.bsky.embed.external#viewLivestream" + } + } + }, + "announcementBanner": { + "type": "object", + "properties": { + "id": { "type": "string", "maxLength": 4096 }, + "title": { "type": "string", "maxLength": 4096 }, + "description": { "type": "string", "maxLength": 4096 }, + "url": { "type": "string", "format": "uri", "maxLength": 4096 }, + "image": { "type": "string", "format": "uri", "maxLength": 4096 }, + "overlayColor": { "type": "string", "maxLength": 4096 }, + "textColor": { "type": "string", "maxLength": 4096 } + } + }, + "appCard": { + "type": "object", + "properties": { + "id": { "type": "string", "maxLength": 4096 }, + "title": { "type": "string", "maxLength": 4096 }, + "description": { "type": "string", "maxLength": 4096 }, + "logo": { "type": "string", "format": "uri", "maxLength": 4096 }, + "backgroundImage": { + "type": "string", + "format": "uri", + "maxLength": 4096 + }, + "overlayColor": { "type": "string", "maxLength": 4096 }, + "textColor": { "type": "string", "maxLength": 4096 }, + "url": { "type": "string", "format": "uri", "maxLength": 4096 }, + "category": { "type": "string", "maxLength": 4096 } + } + } + } +} diff --git a/src/analytics/features/types.ts b/src/analytics/features/types.ts index 2d0be297e..9376cd629 100644 --- a/src/analytics/features/types.ts +++ b/src/analytics/features/types.ts @@ -22,7 +22,7 @@ export enum Features { FollowingV2Enable = 'following_v2:enable', OnboardingInterestsRequiredEnable = 'onboarding:interests:required:enable', ModerationInboxEnable = 'moderation_inbox:enable', - AtmosphereExploreEnable = 'atmosphere_explore:enable', + AtmosphereScreenEnable = 'atmosphere_screen:enable', NotificationsV2Enable = 'notifications_v2:enable', ProfileLinksEnable = 'profile_links:enable', diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 4c0468290..f24d4ee09 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -1406,6 +1406,9 @@ export type Events = { */ 'blockedGeoOverlay:shown': {} + // user dismisses the Atmosphere introduction banner + 'atmosphere:nux:bannerDismissed': {} + 'geo:debug': {} /* diff --git a/src/components/Button.tsx b/src/components/Button.tsx index 2c1f7ff3f..352685642 100644 --- a/src/components/Button.tsx +++ b/src/components/Button.tsx @@ -101,6 +101,7 @@ export type ButtonProps = Pick< | 'onPressOut' | 'onFocus' | 'onBlur' + | 'tabIndex' | 'onAccessibilityAction' | 'onAccessibilityEscape' > & diff --git a/src/components/Gallery/README.md b/src/components/Gallery/README.md index dbf88b2f6..4e4ce2244 100644 --- a/src/components/Gallery/README.md +++ b/src/components/Gallery/README.md @@ -1,9 +1,9 @@ # Gallery A horizontal strip of arbitrary content. Each item owns its own width and -height, and the strip is as tall as the tallest item. It handles swiping, -dragging, trackpads, and the arrow keys; it does not crop, resize, or -virtualize anything. +height, and the strip is as tall as the tallest item. An opt-in `stretch` mode +lets slides share that height. It handles swiping, dragging, trackpads, and the +arrow keys; it does not crop or virtualize anything. ```tsx import * as Gallery from '#/components/Gallery' @@ -35,6 +35,8 @@ except: - `src/components/Gallery/**`: this implementation, its tests, and its Storybook - `src/components/images/Gallery/**`: the image wrapper and its tests +- `src/screens/Atmosphere/components/ExploreGallery.tsx`: the Atmosphere Explore + card carousel wrapper - `src/view/screens/Storybook/Storybook.tsx`: the page that shows the Storybook A new configured wrapper opts in by adding its own directory to that list when @@ -77,6 +79,7 @@ Anything else, at any size: | `label` | Required, translated. Names the carousel for assistive tech. | | `testID` | Optional. | | `ref` | Optional `GalleryRef`, see below. | +| `stretch` | Optional boolean, default false. Stretch slides to the tallest sibling. | | `onIndexChange` | `(index, previousIndex) => void`. Called when the user navigates to a different item. | | `children` | `Gallery.Item`s. Fragments, arrays, and conditional `null`s are flattened. | @@ -100,8 +103,9 @@ a nearby one. | `testID` | Optional. | | `children` | A node, or a function, see "Focus" below. | -The item wraps its children in a view that is measured as it is: never -stretched, and given no width, aspect ratio, or height by the gallery. +The item wraps its children in a view with no imposed width, aspect ratio, or +height. By default it stays at its intrinsic height; with `Root stretch` its +wrapper stretches to the tallest sibling. ### `GalleryRef` @@ -139,7 +143,13 @@ with the padded content. children and the two would depend on each other. - The strip is as tall as its tallest current item, and follows items as they grow, shrink, or leave. An item wider than the gallery scrolls rather than - shrinking. Items are aligned to the top. + shrinking. Items are aligned to the top by default. +- With `stretch`, the flex row determines its own height instead of applying a + measured height back to it. This lets it shrink when the tallest child shrinks + or leaves. To fill a slide, use `flexGrow: 1` on the card and any intermediate + wrappers. Keep image dimensions/aspect ratios on an inner frame rather than + stretching the image itself. The Atmosphere Explore wrapper uses this mode; + post-image galleries retain intrinsic sizing. - The space between items is fixed at 8, since the navigation math depends on it. - An empty gallery takes up no height. @@ -208,6 +218,9 @@ pnpm test --runInBand src/components/Gallery/__tests__ src/components/images/Gal - Mixed content: every card keeps its size, the strip is as tall as the tallest card, and the wide card scrolls instead of being cropped. +- Stretching cards: all card backgrounds share a height. Toggle tall content + and remove/re-add the tallest card; the row must grow and shrink without a + stale height. Check rotation and larger font sizes too. - Changing content: add, remove, reverse, tall/short and wide/narrow all resize the strip without stale offsets. Neither these nor "Reveal last" increase the navigation event count; swiping, dragging, and arrow keys do. diff --git a/src/components/Gallery/Storybook.tsx b/src/components/Gallery/Storybook.tsx index 2b33313b9..27757b476 100644 --- a/src/components/Gallery/Storybook.tsx +++ b/src/components/Gallery/Storybook.tsx @@ -51,6 +51,7 @@ export function GalleryStorybook() { + @@ -309,6 +310,88 @@ function MixedContent() { ) } +/** Equal-height cards that can shrink again when content changes or leaves. */ +function StretchingContent() { + const t = useTheme() + const {t: l} = useLingui() + const [expanded, setExpanded] = useState(true) + const [showTallest, setShowTallest] = useState(true) + + return ( +
Stretching cards} + descriptionText={ + + Cards stretch to the tallest sibling. Shortening or removing the tall + card should let the whole row shrink again. + + }> + + + + + + {[0, 1, ...(showTallest ? [2] : [])].map(index => ( + + + + Card {index} + + {index === 1 ? ( + + A little more content than the first card. + + ) : index === 2 && expanded ? ( + + + This card has enough text to wrap over many lines. Its + siblings should stretch to match its height without + stretching any images or imposing a fixed height. When this + text disappears, all of the cards should shrink again. + + + ) : null} + + + ))} + +
+ ) +} + /** * Children that handle their own presses, text, and focus. */ diff --git a/src/components/Gallery/__tests__/Gallery.test.tsx b/src/components/Gallery/__tests__/Gallery.test.tsx index e878e0d11..7fb3952e1 100644 --- a/src/components/Gallery/__tests__/Gallery.test.tsx +++ b/src/components/Gallery/__tests__/Gallery.test.tsx @@ -33,7 +33,14 @@ jest.mock('#/view/shell/BlockDrawerGesture', () => ({ BlockDrawerGesture: ({children}: {children: React.ReactNode}) => children, })) jest.mock('#/alf', () => ({ - atoms: new Proxy({}, {get: () => ({})}), + atoms: { + w_full: {width: '100%'}, + align_start: {alignItems: 'flex-start'}, + align_stretch: {alignItems: 'stretch'}, + self_start: {alignSelf: 'flex-start'}, + self_stretch: {alignSelf: 'stretch'}, + flex_shrink_0: {flexShrink: 0}, + }, web: () => undefined, })) @@ -281,6 +288,102 @@ describe('Gallery sizing', () => { }) }) +describe('Gallery stretching', () => { + it('keeps intrinsic sizing as the default', () => { + render( + + {card('short', 100, 80)} + , + ) + expect(flat(scrollView().props.contentContainerStyle).alignItems).toBe( + 'flex-start', + ) + expect(flat(screen.getByTestId('short').props.style).alignSelf).toBe( + 'flex-start', + ) + layout('short', 100, 80) + expect(rootHeight()).toBe(80) + }) + + it('stretches slides without feeding their measured height back into the row', () => { + render( + + {card('short', 100, 80)} + {card('tall', 140, 240)} + , + ) + expect(flat(scrollView().props.contentContainerStyle).alignItems).toBe( + 'stretch', + ) + for (const id of ['short', 'tall']) { + const style = flat(screen.getByTestId(id).props.style) + expect(style.alignSelf).toBe('stretch') + expect(style.width).toBeUndefined() + expect(style.height).toBeUndefined() + layout(id, id === 'short' ? 100 : 140, 240) + } + expect(rootHeight()).toBeUndefined() + expect(flat(scrollView().props.style).height).toBeUndefined() + expect( + flat(scrollView().props.contentContainerStyle).height, + ).toBeUndefined() + }) + + it('does not retain stretched heights after removing or shrinking content', () => { + const gallery = (tall: boolean) => ( + + {card('short', 100, 80)} + {tall ? card('tall', 140, 240) : null} + + ) + const {rerender} = render(gallery(true)) + layout('short', 100, 240) + layout('tall', 140, 240) + rerender(gallery(false)) + expect(rootHeight()).toBeUndefined() + layout('short', 100, 80) + expect(rootHeight()).toBeUndefined() + expect(flat(screen.getByTestId('short').props.style).height).toBeUndefined() + }) + + it('can switch between intrinsic and stretched sizing', () => { + const gallery = (stretch: boolean) => ( + + {card('short', 100, 80)} + {card('tall', 140, 240)} + + ) + const {rerender} = render(gallery(false)) + layout('short', 100, 80) + layout('tall', 140, 240) + expect(rootHeight()).toBe(240) + rerender(gallery(true)) + expect(rootHeight()).toBeUndefined() + expect(flat(screen.getByTestId('short').props.style).alignSelf).toBe( + 'stretch', + ) + rerender(gallery(false)) + expect(rootHeight()).toBe(240) + expect(flat(screen.getByTestId('short').props.style).alignSelf).toBe( + 'flex-start', + ) + }) + + it('does not impose a height on empty or single-item stretched galleries', () => { + const {rerender} = render( + , + ) + expect(rootHeight()).toBeUndefined() + rerender( + + {card('only', 100, 80)} + , + ) + layout('only', 100, 80) + expect(rootHeight()).toBeUndefined() + }) +}) + describe('Gallery accessibility', () => { it('labels the carousel and its slides', () => { render( diff --git a/src/components/Gallery/index.tsx b/src/components/Gallery/index.tsx index 6eb4c85a1..38cc21efe 100644 --- a/src/components/Gallery/index.tsx +++ b/src/components/Gallery/index.tsx @@ -55,6 +55,7 @@ const ItemContext = createContext<{ isFocusTarget: boolean /** Whether to apply a roving tabIndex at all */ rovingEnabled: boolean + stretch: boolean onItemLayout: (key: string, size: Size) => void registerFocusNode: (key: string, node: unknown) => void onItemFocus: (index: number) => void @@ -63,8 +64,8 @@ ItemContext.displayName = 'GalleryItemContext' /** * A horizontal strip of arbitrary content. Each child must render a - * `Gallery.Item`. Children own their width and height; the strip is as tall - * as the tallest one. + * `Gallery.Item`. Children own their width and intrinsic height; the strip is + * as tall as the tallest one. Opt into `stretch` to equalize slide heights. * * Children are all rendered eagerly, so this is meant for a small number of * items rather than an unbounded list. @@ -75,12 +76,15 @@ export function Root({ testID, ref, onIndexChange, + stretch = false, }: { children?: React.ReactNode /** Translated accessible label for the whole gallery */ label: string testID?: string ref?: React.Ref + /** Stretch slides to the tallest sibling, without imposing child heights. */ + stretch?: boolean /** * Called when the user navigates to a different item via native swipe, * mouse drag, arrow keys, or Safari horizontal wheel events. Browser touch @@ -369,7 +373,8 @@ export function Root({ style={[ a.w_full, { - height: maxHeight > 0 ? maxHeight : undefined, + /* Let the row size itself so stretched measurements cannot lock its height. */ + height: !stretch && maxHeight > 0 ? maxHeight : undefined, overflow: 'visible', }, ]} @@ -418,7 +423,7 @@ export function Root({ web({overscrollBehaviorX: 'contain'}), ]} contentContainerStyle={[ - a.align_start, + stretch ? a.align_stretch : a.align_start, { gap: ITEM_GAP, paddingLeft: insetLeft, @@ -433,6 +438,7 @@ export function Root({ index, isFocusTarget: index === activeFocusIndex, rovingEnabled, + stretch, onItemLayout, registerFocusNode, onItemFocus, @@ -447,8 +453,8 @@ export function Root({ } /** - * One slide. Measured at whatever size its children take up, so it never - * imposes a width or height. Pass a function as children to receive props for + * One slide. Never imposes a width or height; the root can opt into stretching + * slides to the tallest sibling. Pass a function as children to receive props for * attaching to an interactive element that should be the keyboard focus target * for this slide, instead of the slide itself. */ @@ -471,6 +477,7 @@ export function Item({ index, isFocusTarget, rovingEnabled, + stretch, onItemLayout, registerFocusNode, onItemFocus, @@ -499,7 +506,7 @@ export function Item({ tabIndex, ...(IS_WEB ? {onFocus} : null), })} - style={[a.flex_shrink_0, a.self_start]} + style={[a.flex_shrink_0, stretch ? a.self_stretch : a.self_start]} onLayout={(e: LayoutChangeEvent) => { const {width, height} = e.nativeEvent.layout onItemLayout(itemKey, {width, height}) diff --git a/src/components/Link.tsx b/src/components/Link.tsx index 8e5891f3b..f2df1811a 100644 --- a/src/components/Link.tsx +++ b/src/components/Link.tsx @@ -4,6 +4,7 @@ import { Linking, type NativeSyntheticEvent, type TargetedEvent, + type View, } from 'react-native' import {sanitizeUrl} from '@braintree/sanitize-url' import {useLingui} from '@lingui/react/macro' @@ -300,6 +301,10 @@ export function useLink({ export type LinkProps = Omit & Omit & { overridePresentation?: boolean + /** + * Forwarded to the underlying `Button`, e.g. for a roving focus target. + */ + ref?: React.Ref> } /** diff --git a/src/components/Post/Embed/StandardSiteEmbed/index.tsx b/src/components/Post/Embed/StandardSiteEmbed/index.tsx index 28d110e28..6368bfb31 100644 --- a/src/components/Post/Embed/StandardSiteEmbed/index.tsx +++ b/src/components/Post/Embed/StandardSiteEmbed/index.tsx @@ -16,7 +16,7 @@ import {useInteractionState} from '#/components/hooks/useInteractionState' import {ArrowTopRight_Stroke2_Corner0_Rounded as ArrowTopRightIcon} from '#/components/icons/Arrow' import {Clock_Stroke2_Corner0_Rounded as Clock} from '#/components/icons/Clock' import {StandardSite} from '#/components/icons/community/StandardSite' -import {Link} from '#/components/Link' +import {Link, type LinkProps} from '#/components/Link' import {MediaInsetBorder} from '#/components/MediaInsetBorder' import {matchStandardSitePublisher} from '#/components/Post/Embed/StandardSiteEmbed/publishers' import {StandardSiteMetaRow} from '#/components/Post/Embed/StandardSiteEmbed/StandardSiteMetaRow' @@ -299,7 +299,9 @@ export function PublicationCard({ onLongPress, themeColors, style, + linkProps, onEmbedInteractionCallback, + hideSubscribe, }: ssTypes.CommonProps & ssTypes.PreviewProps & ssTypes.PublicApiProps & { @@ -307,6 +309,13 @@ export function PublicationCard({ onLongPress?: () => void themeColors: ssTypes.ThemeColors style?: StyleProp + /** + * Focus plumbing for hosts such as carousels. The ref applies to the + * primary link only; the subscribe link receives just `tabIndex` and + * `onFocus`. + */ + linkProps?: Pick + hideSubscribe?: boolean }) { const t = useTheme() const {t: l} = useLingui() @@ -319,6 +328,12 @@ export function PublicationCard({ if (!view.source) return null + /* The primary link alone takes the ref; it is the host's focus target. */ + const subscribeLinkProps = linkProps && { + tabIndex: linkProps.tabIndex, + onFocus: linkProps.onFocus, + } + return ( { + onInteract() + linkProps?.onFocus?.(e) + }} onBlur={onInteractOut} style={[a.absolute, a.inset_0]}> <> @@ -352,7 +372,6 @@ export function PublicationCard({ - {gtPhone && ( + {gtPhone && !hideSubscribe && ( )} - - {view.description && ( + + {!!view.description && ( {view.description} @@ -418,6 +438,7 @@ export function PublicationCard({ preview={preview} view={view} style={[!gtPhone && [a.w_full, a.justify_center]]} + linkProps={subscribeLinkProps} onEmbedInteractionCallback={onEmbedInteractionCallback} /> @@ -431,11 +452,13 @@ export function SubscribeButton({ preview, view, style, + linkProps, onEmbedInteractionCallback, }: ssTypes.CommonProps & ssTypes.PreviewProps & ssTypes.PublicApiProps & { style?: StyleProp + linkProps?: Pick }) { const ax = useAnalytics() const {t: l} = useLingui() @@ -516,6 +539,8 @@ export function SubscribeButton({ label={label} size="small" color="secondary_inverted" + tabIndex={linkProps?.tabIndex} + onFocus={linkProps?.onFocus} style={[ style, a.gap_sm, diff --git a/src/screens/Atmosphere/ActivityTab.tsx b/src/screens/Atmosphere/ActivityTab.tsx new file mode 100644 index 000000000..b1544cfd2 --- /dev/null +++ b/src/screens/Atmosphere/ActivityTab.tsx @@ -0,0 +1,45 @@ +import {View} from 'react-native' +import Animated, {useAnimatedStyle} from 'react-native-reanimated' +import {Trans} from '@lingui/react/macro' + +import {useShellLayout} from '#/state/shell/shell-layout' +import {atoms as a, useTheme} from '#/alf' +import {Earth_Stroke2_Corner0_Rounded as EarthIcon} from '#/components/icons/Earth' +import * as Layout from '#/components/Layout' +import {Text} from '#/components/Typography' + +export function AtmosphereActivityTab() { + const t = useTheme() + const {footerHeight} = useShellLayout() + const animatedStyle = useAnimatedStyle(() => ({ + paddingBottom: footerHeight.get(), + })) + + return ( + + + + + + + Your Atmosphere is quiet + + + + The Atmosphere is the open network Bluesky is built on. When + people you follow are active on the Atmosphere, you can see it + here. + + + + + + + ) +} diff --git a/src/screens/Atmosphere/ExploreTab.tsx b/src/screens/Atmosphere/ExploreTab.tsx new file mode 100644 index 000000000..9e8afad66 --- /dev/null +++ b/src/screens/Atmosphere/ExploreTab.tsx @@ -0,0 +1,83 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' +import { + getAtmosphereAnnouncementBanner, + getAtmosphereApps, + getAtmosphereArticles, + getAtmosphereLivestreams, + getAtmospherePhotos, + getAtmospherePublications, +} from '#/screens/Atmosphere/data/exploreData' +import {useAtmosphereExploreQuery} from '#/screens/Atmosphere/data/useAtmosphereExploreQuery' +import {atoms as a} from '#/alf' +import * as Layout from '#/components/Layout' +import {Loader} from '#/components/Loader' +import {AnnouncementBanner} from './components/AnnouncementBanner' +import {AtmosphereNux} from './components/AtmosphereNux' +import {ExploreGalleryBleed} from './components/ExploreGallery' +import {FeaturedApps} from './components/FeaturedApps' +import {FeaturedArticles} from './components/FeaturedArticles' +import {FeaturedLivestreams} from './components/FeaturedLivestreams' +import {FeaturedPhotos} from './components/FeaturedPhotos' +import {FeaturedPublications} from './components/FeaturedPublications' + +export function AtmosphereExploreTab() { + const {t: l} = useLingui() + const {data, isError, isPending, refetch} = useAtmosphereExploreQuery() + + const errorMessage = ( + void refetch()} + /> + ) + + if (!data) { + return ( + + {isPending ? ( + + + + ) : isError ? ( + errorMessage + ) : undefined} + + ) + } + + const announcementBanner = getAtmosphereAnnouncementBanner(data) + + return ( + + + + {isError ? errorMessage : undefined} + + {announcementBanner ? ( + + ) : undefined} + + + + + + + + + ) +} diff --git a/src/screens/Atmosphere/__tests__/ExploreTab.test.tsx b/src/screens/Atmosphere/__tests__/ExploreTab.test.tsx new file mode 100644 index 000000000..0d4c30e14 --- /dev/null +++ b/src/screens/Atmosphere/__tests__/ExploreTab.test.tsx @@ -0,0 +1,271 @@ +import {fireEvent, render, screen} from '@testing-library/react-native' + +import {exploreResponseFixture} from '#/screens/Atmosphere/__tests__/fixtures/exploreResponse' +import {livestreamPreviewFixture} from '#/screens/Atmosphere/__tests__/fixtures/livestreamPreview' +import {type AtmosphereData} from '#/screens/Atmosphere/data/exploreData' +import {useAtmosphereExploreQuery} from '#/screens/Atmosphere/data/useAtmosphereExploreQuery' +import {AtmosphereExploreTab} from '#/screens/Atmosphere/ExploreTab' +import {app} from '#/lexicons' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: (message: {message?: string} | string) => + typeof message === 'string' ? message : (message.message ?? ''), + }), +})) + +jest.mock('#/screens/Atmosphere/data/useAtmosphereExploreQuery', () => ({ + useAtmosphereExploreQuery: jest.fn(), +})) + +jest.mock('#/components/Layout', () => { + const {View} = + jest.requireActual('react-native') + return {Content: View} +}) + +jest.mock('#/components/Loader', () => { + const {View} = + jest.requireActual('react-native') + return {Loader: () => } +}) + +jest.mock('#/view/com/util/error/ErrorMessage', () => { + const {Pressable, Text, View} = + jest.requireActual('react-native') + return { + ErrorMessage: ({ + message, + onPressTryAgain, + }: { + message: string + onPressTryAgain: () => void + }) => ( + + {message} + + + ), + } +}) + +jest.mock('#/screens/Atmosphere/components/AtmosphereNux', () => { + const {Text} = + jest.requireActual('react-native') + return {AtmosphereNux: () => nux} +}) + +jest.mock('#/screens/Atmosphere/components/AnnouncementBanner', () => { + const {Text} = + jest.requireActual('react-native') + return { + AnnouncementBanner: ({banner}: {banner: {title: string}}) => ( + {`banner:${banner.title}`} + ), + } +}) + +function mockSection(name: string, prop: string) { + const {Text} = + jest.requireActual('react-native') + return ({[prop]: items}: Record) => + items.length ? ( + {`${name}:${items.map(item => item.title).join(',')}`} + ) : null +} + +jest.mock('#/screens/Atmosphere/components/FeaturedArticles', () => ({ + FeaturedArticles: mockSection('articles', 'articles'), +})) +jest.mock('#/screens/Atmosphere/components/FeaturedPublications', () => ({ + FeaturedPublications: mockSection('publications', 'publications'), +})) +jest.mock('#/screens/Atmosphere/components/FeaturedApps', () => ({ + FeaturedApps: mockSection('apps', 'apps'), +})) +jest.mock('#/screens/Atmosphere/components/FeaturedLivestreams', () => ({ + FeaturedLivestreams: mockSection('livestreams', 'livestreams'), +})) +jest.mock('#/screens/Atmosphere/components/FeaturedPhotos', () => ({ + FeaturedPhotos: mockSection('photos', 'photos'), +})) + +const mockQuery = jest.mocked(useAtmosphereExploreQuery) +const refetch = jest.fn() + +function setQuery( + result: Partial>, +) { + mockQuery.mockReturnValue({ + data: undefined, + isError: false, + isPending: false, + refetch, + ...result, + } as never) +} + +const data: AtmosphereData = { + announcementBanner: {title: 'Launch', url: 'https://example.com/launch'}, + articles: { + items: [ + { + featured: true, + view: { + uri: 'https://example.com/article', + title: 'Live article', + description: '', + }, + }, + ], + }, + publications: {items: []}, + photos: {items: []}, + livestreams: {items: []}, + apps: [{id: 'app', title: 'Live app', url: 'https://example.com/app'}], +} + +beforeEach(() => { + jest.clearAllMocks() +}) + +describe('AtmosphereExploreTab', () => { + it('shows an accessible loader while the first request is pending', () => { + setQuery({isPending: true}) + render() + + expect(screen.getByTestId('atmosphereExploreTab')).toBeTruthy() + expect(screen.getByTestId('loader')).toBeTruthy() + expect(screen.getByLabelText('Loading Atmosphere content')).toBeTruthy() + expect(screen.queryByText('nux')).toBeNull() + }) + + it('shows a retryable error without raw error details on first load failure', () => { + setQuery({isError: true, error: new Error('socket hang up')}) + render() + + expect( + screen.getByText('Could not load Atmosphere content. Please try again.'), + ).toBeTruthy() + expect(screen.queryByText(/socket hang up/)).toBeNull() + expect(screen.queryByTestId('loader')).toBeNull() + + fireEvent.press(screen.getByTestId('retry')) + expect(refetch).toHaveBeenCalledTimes(1) + }) + + it('renders live content and hides empty sections without preview fallbacks', () => { + setQuery({data}) + render() + + expect(screen.getByText('nux')).toBeTruthy() + expect(screen.getByText('banner:Launch')).toBeTruthy() + expect(screen.getByText('articles:Live article')).toBeTruthy() + expect(screen.getByText('apps:Live app')).toBeTruthy() + expect(screen.queryByText(/^livestreams:/)).toBeNull() + expect(screen.queryByText(/^photos:/)).toBeNull() + expect( + screen.queryByText(livestreamPreviewFixture[0].view.title, { + exact: false, + }), + ).toBeNull() + expect(screen.queryByTestId('retry')).toBeNull() + }) + + it('renders nonfeatured recommendations in server order', () => { + setQuery({ + data: { + ...data, + articles: { + recIdStr: '18446744073709551615', + items: ['Second', 'First'].map(title => ({ + featured: false, + view: {uri: `https://example.com/${title}`, title, description: ''}, + })), + }, + }, + }) + render() + + expect(screen.getByText('articles:Second,First')).toBeTruthy() + }) + + it('hides only articles when recommendations are empty', () => { + const populated = + app.bsky.unspecced.getAtmosphereExploreTab.$output.schema.parse({ + ...exploreResponseFixture, + articles: {items: [], recIdStr: '18446744073709551615'}, + livestreams: {items: livestreamPreviewFixture}, + }) + setQuery({data: populated}) + render() + + expect(screen.queryByText(/^articles:/)).toBeNull() + expect(screen.getByText(/^photos:/)).toBeTruthy() + expect(screen.getByText(/^livestreams:/)).toBeTruthy() + expect(screen.getByText(/^apps:/)).toBeTruthy() + expect(screen.getByText(/^banner:/)).toBeTruthy() + }) + + it('renders publications from the response, even when articles are empty', () => { + setQuery({ + data: { + ...exploreResponseFixture, + articles: {items: []}, + photos: {items: []}, + apps: [], + }, + }) + render() + + expect( + screen.getByText( + `publications:${exploreResponseFixture.publications.items[0].view.title}`, + ), + ).toBeTruthy() + expect(screen.queryByText(/^articles:/)).toBeNull() + }) + + it('renders a publication-only response and hides empty publications', () => { + setQuery({data: {...exploreResponseFixture, publications: {items: []}}}) + render() + + expect(screen.queryByText(/^publications:/)).toBeNull() + expect(screen.getByText(/^articles:/)).toBeTruthy() + }) + + it('renders the NUX only for an empty response without a banner', () => { + setQuery({ + data: { + articles: {items: []}, + publications: {items: []}, + photos: {items: []}, + livestreams: {items: []}, + apps: [], + }, + }) + render() + + expect(screen.getByText('nux')).toBeTruthy() + expect(screen.queryByText(/^banner:/)).toBeNull() + expect( + screen.queryByText(/^(articles|publications|apps|photos|livestreams):/), + ).toBeNull() + }) + + it('keeps cached content and offers retry when a background refetch fails', () => { + setQuery({data, isError: true}) + render() + + expect(screen.getByText('articles:Live article')).toBeTruthy() + expect( + screen.getByText('Could not load Atmosphere content. Please try again.'), + ).toBeTruthy() + fireEvent.press(screen.getByTestId('retry')) + expect(refetch).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/screens/Atmosphere/__tests__/fixtures/exploreResponse.ts b/src/screens/Atmosphere/__tests__/fixtures/exploreResponse.ts new file mode 100644 index 000000000..448716a19 --- /dev/null +++ b/src/screens/Atmosphere/__tests__/fixtures/exploreResponse.ts @@ -0,0 +1,102 @@ +import {type AtmosphereData} from '#/screens/Atmosphere/data/exploreData' +import {type app} from '#/lexicons' + +const author: app.bsky.actor.defs.ProfileViewBasic = { + $type: 'app.bsky.actor.defs#profileViewBasic', + did: 'did:plc:6ayddqghxhciedbaofoxkcbs', + handle: 'author.test', + avatar: 'https://example.com/avatar.jpg', +} + +const publication: app.bsky.embed.external.ViewArticlePublication = { + $type: 'app.bsky.embed.external#viewArticlePublication', + uri: 'https://example.com/publication', + title: 'Test publication', + description: 'A publication description', + logo: 'https://example.com/logo.jpg', + theme: { + background: '#ffffff', + foreground: '#000000', + accent: '#123456', + accentForeground: '#ffffff', + }, + subscriptionCount: 1, + subscribers: [author], +} + +const image = { + $type: 'app.bsky.embed.external#viewGalleryImage' as const, + thumbnail: 'https://example.com/thumbnail.jpg' as const, + fullsize: 'https://example.com/fullsize.jpg' as const, + alt: 'A test photo', +} + +/** Small synthetic response for schema, mapping, and screen tests. */ +export const exploreResponseFixture: AtmosphereData = { + announcementBanner: { + id: 'banner', + title: 'Test announcement', + description: 'An announcement description', + url: 'https://example.com/announcement', + image: 'https://example.com/banner.jpg', + overlayColor: '#000000', + textColor: '#ffffff', + }, + articles: { + items: [ + { + featured: true, + view: { + $type: 'app.bsky.embed.external#viewArticle', + uri: 'https://example.com/first-article', + title: ' First article ', + description: '', + image: 'https://example.com/article.jpg', + publisher: publication, + associatedProfiles: [author], + likeCount: 1, + likers: [author], + }, + }, + { + featured: true, + view: { + $type: 'app.bsky.embed.external#viewArticle', + uri: 'https://example.com/second-article', + title: 'Second article', + description: 'An article description', + publisher: publication, + }, + }, + ], + }, + publications: {items: [{featured: true, view: publication}]}, + photos: { + items: ['First photo', 'Second photo'].map((title, index) => ({ + featured: true, + view: { + $type: 'app.bsky.embed.external#viewGallery', + uri: `https://example.com/gallery-${index}`, + title, + description: '', + items: [image], + associatedProfiles: [author], + likeCount: 2, + likers: [author], + }, + })), + }, + livestreams: {items: []}, + apps: [ + { + id: 'app', + title: 'Test app', + description: 'An app description', + logo: 'https://example.com/app-logo.jpg', + backgroundImage: 'https://example.com/app-background.jpg', + overlayColor: '#123456', + textColor: '#ffffff', + url: 'https://example.com/app', + }, + ], +} diff --git a/src/screens/Atmosphere/__tests__/fixtures/livestreamPreview.ts b/src/screens/Atmosphere/__tests__/fixtures/livestreamPreview.ts new file mode 100644 index 000000000..99d492bd8 --- /dev/null +++ b/src/screens/Atmosphere/__tests__/fixtures/livestreamPreview.ts @@ -0,0 +1,62 @@ +/** + * Raw livestream preview data for tests. The live endpoint can return + * livestreams, so this is not used by the app. Parse with + * `app.bsky.unspecced.getAtmosphereExploreTab.$output.schema` on the full + * response envelope before passing it to the adapters. + */ +const previewAuthorProfile = { + $type: 'app.bsky.actor.defs#profileViewBasic', + did: 'did:plc:ifn645rwvsuolxg7o3w7ouo4', + handle: 'aster.id', + displayName: 'Aster', + avatar: + 'https://cdn.bsky.app/img/avatar/plain/did:plc:ifn645rwvsuolxg7o3w7ouo4/bafkreicid7hoyx5d2if24eryyhb3lg4ioy2mdrmiriga3k2cay6k5io4ta', +} + +export const livestreamPreviewFixture = [ + { + featured: true, + view: { + $type: 'app.bsky.embed.external#viewLivestream', + uri: 'https://example.com/livestreams/open-publishing', + title: 'A look at open publishing', + description: + 'A live conversation about building independent spaces for writing and research.', + active: true, + image: + 'https://cdn.bsky.app/img/feed_thumbnail/plain/did:plc:ifn645rwvsuolxg7o3w7ouo4/bafkreidvntdnpe3nzj7wkdxjuhutbf5g7lozznoe7gosqgw3xc2mx3i3om@webp', + startedAt: '2026-10-07T17:00:00.000Z', + associatedProfiles: [previewAuthorProfile], + }, + }, + { + featured: true, + view: { + $type: 'app.bsky.embed.external#viewLivestream', + uri: 'https://example.com/livestreams/community-q-and-a', + title: 'Community Q&A', + description: + 'Questions and answers about the latest community tools and updates.', + active: false, + image: + 'https://cdn.bsky.app/img/feed_thumbnail/plain/did:plc:v46ojbiop5ebs5h7gaomixcc/bafkreiaqvoj5onk5t6v6al2jvqkgydicwfpbbjdawwcfdljvgv7n7peyim@png', + endedAt: '2026-10-06T18:00:00.000Z', + associatedProfiles: [previewAuthorProfile], + }, + }, + { + featured: true, + view: { + $type: 'app.bsky.embed.external#viewLivestream', + uri: 'https://example.com/livestreams/creative-coding', + title: 'Creative coding session', + description: + 'A hands-on stream exploring small generative art projects with the community.', + active: true, + image: + 'https://app-cms-production.bsky.workers.dev/images/image-0a7748426cbd27b63c04a608d930120d2beb9727-3000x2000-jpg/large', + startedAt: '2026-10-07T18:30:00.000Z', + associatedProfiles: [previewAuthorProfile], + }, + }, +] diff --git a/src/screens/Atmosphere/components/AnnouncementBanner.tsx b/src/screens/Atmosphere/components/AnnouncementBanner.tsx new file mode 100644 index 000000000..c843997cb --- /dev/null +++ b/src/screens/Atmosphere/components/AnnouncementBanner.tsx @@ -0,0 +1,80 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {LinearGradient} from 'expo-linear-gradient' +import {useLingui} from '@lingui/react/macro' + +import {type AtmosphereAnnouncementBannerData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, utils} from '#/alf' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' + +export function AnnouncementBanner({ + banner, +}: { + banner: AtmosphereAnnouncementBannerData +}) { + const {t: l} = useLingui() + + return ( + + + {banner.image ? ( + + ) : undefined} + {banner.overlayColor ? ( + + ) : undefined} + + + {banner.title} + + {banner.description ? ( + + {banner.description} + + ) : undefined} + + + + ) +} diff --git a/src/screens/Atmosphere/components/AppCard.tsx b/src/screens/Atmosphere/components/AppCard.tsx new file mode 100644 index 000000000..65d31e5c3 --- /dev/null +++ b/src/screens/Atmosphere/components/AppCard.tsx @@ -0,0 +1,85 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {LinearGradient} from 'expo-linear-gradient' +import {useLingui} from '@lingui/react/macro' + +import {type AtmosphereAppCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, utils} from '#/alf' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' + +export function AppCard({app}: {app: AtmosphereAppCardData}) { + const {t: l} = useLingui() + + return ( + + {app.backgroundImage ? ( + + ) : undefined} + {app.overlayColor ? ( + + ) : undefined} + + + {app.logo ? ( + + ) : undefined} + + + {app.title} + + {app.description ? ( + + {app.description} + + ) : undefined} + + + + + ) +} diff --git a/src/screens/Atmosphere/components/ArticleCard.tsx b/src/screens/Atmosphere/components/ArticleCard.tsx new file mode 100644 index 000000000..59de77b42 --- /dev/null +++ b/src/screens/Atmosphere/components/ArticleCard.tsx @@ -0,0 +1,122 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {useLingui} from '@lingui/react/macro' + +import {type AtmosphereArticleCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, useTheme, web} from '#/alf' +import {useInteractionState} from '#/components/hooks/useInteractionState' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' +import {IS_NATIVE} from '#/env' +import {type ExploreGalleryFocusProps} from './ExploreGallery' + +export function ArticleCard({ + article, + width, + galleryFocus, +}: { + article: AtmosphereArticleCardData + width?: number + galleryFocus?: ExploreGalleryFocusProps +}) { + const {t: l} = useLingui() + const t = useTheme() + const { + state: interacted, + onIn: onInteract, + onOut: onInteractOut, + } = useInteractionState() + + return ( + + + { + onInteract() + galleryFocus?.onFocus() + }} + onBlur={onInteractOut} + style={[a.flex_col, a.flex_1, a.w_full]}> + + {article.image ? ( + + ) : undefined} + + + {article.publisher || article.publisherAvatar ? ( + + {article.publisherAvatar ? ( + + ) : undefined} + {article.publisher ? ( + + {article.publisher} + + ) : undefined} + + ) : undefined} + + + {article.title} + + {article.description ? ( + + {article.description} + + ) : undefined} + + + + + + ) +} diff --git a/src/screens/Atmosphere/components/AtmosphereNux.tsx b/src/screens/Atmosphere/components/AtmosphereNux.tsx new file mode 100644 index 000000000..10c4c1367 --- /dev/null +++ b/src/screens/Atmosphere/components/AtmosphereNux.tsx @@ -0,0 +1,89 @@ +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' + +import {HITSLOP_10} from '#/lib/constants' +import {Nux, useNux, useSaveNux} from '#/state/queries/nuxs' +import {atoms as a, tokens} from '#/alf' +import {Button, ButtonIcon} from '#/components/Button' +import {GradientFill} from '#/components/GradientFill' +import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/TimesLarge' +import * as Toast from '#/components/Toast' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' + +export function AtmosphereNux() { + const {t: l} = useLingui() + const ax = useAnalytics() + const {nux} = useNux(Nux.AtmosphereNux) + const {mutate: save, variables} = useSaveNux() + + if (variables || nux?.completed) return null + + const dismiss = () => { + Toast.show(`TEMP: Dismissed the banner. Will remove for production.`) + return + save({ + id: Nux.AtmosphereNux, + completed: true, + data: undefined, + }) + ax.metric('atmosphere:nux:bannerDismissed', {}) + } + + return ( + + + {/* + + */} + + + + Discover the Atmosphere + + + + Bluesky is part of a growing network of hundreds of social apps. + Your account unlocks them all. + + + + + + + ) +} diff --git a/src/screens/Atmosphere/components/ExploreGallery.tsx b/src/screens/Atmosphere/components/ExploreGallery.tsx new file mode 100644 index 000000000..153b2fd3f --- /dev/null +++ b/src/screens/Atmosphere/components/ExploreGallery.tsx @@ -0,0 +1,47 @@ +import {View} from 'react-native' + +import {atoms as a} from '#/alf' +import * as GalleryPrimitive from '#/components/Gallery' + +/** + * The generic gallery's own `Bleed`, re-exported so Explore shares exactly one + * bleed context with the galleries rendered inside it. + */ +export const ExploreGalleryBleed = GalleryPrimitive.Bleed + +export type ExploreGalleryFocusProps = GalleryPrimitive.ItemFocusProps + +/** + * Horizontal card carousel for the Atmosphere Explore sections. Cards own + * their own width and stretch to the tallest card in the strip. + */ +export function ExploreGallery({ + items, + label, + testID, + renderItem, +}: { + items: T[] + label: string + testID: string + renderItem: (item: T, focusProps: ExploreGalleryFocusProps) => React.ReactNode +}) { + return ( + + {items.map(item => ( + + {focusProps => ( + /* + * The bottom allowance lives inside the item so it is measured and + * scrolled with the card, which keeps card shadows from being + * clipped. + */ + + {renderItem(item, focusProps)} + + )} + + ))} + + ) +} diff --git a/src/screens/Atmosphere/components/ExploreSectionHeader.tsx b/src/screens/Atmosphere/components/ExploreSectionHeader.tsx new file mode 100644 index 000000000..4eb1d2f96 --- /dev/null +++ b/src/screens/Atmosphere/components/ExploreSectionHeader.tsx @@ -0,0 +1,10 @@ +import {atoms as a} from '#/alf' +import {Text} from '#/components/Typography' + +export function ExploreSectionHeader({title}: {title: React.ReactNode}) { + return ( + + {title} + + ) +} diff --git a/src/screens/Atmosphere/components/FeaturedApps.tsx b/src/screens/Atmosphere/components/FeaturedApps.tsx new file mode 100644 index 000000000..1fb485570 --- /dev/null +++ b/src/screens/Atmosphere/components/FeaturedApps.tsx @@ -0,0 +1,24 @@ +import {View} from 'react-native' +import {Trans} from '@lingui/react/macro' + +import {type AtmosphereAppCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a} from '#/alf' +import {Text} from '#/components/Typography' +import {AppCard} from './AppCard' + +export function FeaturedApps({apps}: {apps: AtmosphereAppCardData[]}) { + if (!apps.length) return null + + return ( + + + Apps on the Atmosphere + + + {apps.map(app => ( + + ))} + + + ) +} diff --git a/src/screens/Atmosphere/components/FeaturedArticles.tsx b/src/screens/Atmosphere/components/FeaturedArticles.tsx new file mode 100644 index 000000000..ad7278ba1 --- /dev/null +++ b/src/screens/Atmosphere/components/FeaturedArticles.tsx @@ -0,0 +1,38 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {type AtmosphereArticleCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a} from '#/alf' +import {ArticleCard} from './ArticleCard' +import {ExploreGallery} from './ExploreGallery' +import {ExploreSectionHeader} from './ExploreSectionHeader' + +const CARD_WIDTH = 250 + +export function FeaturedArticles({ + articles, +}: { + articles: AtmosphereArticleCardData[] +}) { + const {t: l} = useLingui() + + if (!articles.length) return null + + return ( + + + ( + + )} + /> + + ) +} diff --git a/src/screens/Atmosphere/components/FeaturedLivestreams.tsx b/src/screens/Atmosphere/components/FeaturedLivestreams.tsx new file mode 100644 index 000000000..a461f41a9 --- /dev/null +++ b/src/screens/Atmosphere/components/FeaturedLivestreams.tsx @@ -0,0 +1,38 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {type AtmosphereLivestreamCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a} from '#/alf' +import {ExploreGallery} from './ExploreGallery' +import {ExploreSectionHeader} from './ExploreSectionHeader' +import {LivestreamCard} from './LivestreamCard' + +const CARD_WIDTH = 214 + +export function FeaturedLivestreams({ + livestreams, +}: { + livestreams: AtmosphereLivestreamCardData[] +}) { + const {t: l} = useLingui() + + if (!livestreams.length) return null + + return ( + + + ( + + )} + /> + + ) +} diff --git a/src/screens/Atmosphere/components/FeaturedPhotos.tsx b/src/screens/Atmosphere/components/FeaturedPhotos.tsx new file mode 100644 index 000000000..3808b56ff --- /dev/null +++ b/src/screens/Atmosphere/components/FeaturedPhotos.tsx @@ -0,0 +1,32 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {type AtmospherePhotoCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a} from '#/alf' +import {ExploreGallery} from './ExploreGallery' +import {ExploreSectionHeader} from './ExploreSectionHeader' +import {PhotoCard} from './PhotoCard' + +const CARD_WIDTH = 225 + +export function FeaturedPhotos({photos}: {photos: AtmospherePhotoCardData[]}) { + const {t: l} = useLingui() + + if (!photos.length) return null + + return ( + + + ( + + + + )} + /> + + ) +} diff --git a/src/screens/Atmosphere/components/FeaturedPublications.tsx b/src/screens/Atmosphere/components/FeaturedPublications.tsx new file mode 100644 index 000000000..673fbfd95 --- /dev/null +++ b/src/screens/Atmosphere/components/FeaturedPublications.tsx @@ -0,0 +1,38 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {type AtmospherePublicationCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a} from '#/alf' +import {ExploreGallery} from './ExploreGallery' +import {ExploreSectionHeader} from './ExploreSectionHeader' +import {PublicationCard} from './PublicationCard' + +const CARD_WIDTH = 320 + +export function FeaturedPublications({ + publications, +}: { + publications: AtmospherePublicationCardData[] +}) { + const {t: l} = useLingui() + + if (!publications.length) return null + + return ( + + + ( + + )} + /> + + ) +} diff --git a/src/screens/Atmosphere/components/LivestreamCard.tsx b/src/screens/Atmosphere/components/LivestreamCard.tsx new file mode 100644 index 000000000..2de31652e --- /dev/null +++ b/src/screens/Atmosphere/components/LivestreamCard.tsx @@ -0,0 +1,194 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {moderateProfile} from '@bsky/sdk/moderation' +import {plural} from '@lingui/core/macro' +import {Trans, useLingui} from '@lingui/react/macro' + +import {sanitizeDisplayName} from '#/lib/strings/display-names' +import {sanitizeHandle} from '#/lib/strings/handles' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {UserAvatar} from '#/view/com/util/UserAvatar' +import {type AtmosphereLivestreamCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, useTheme} from '#/alf' +import {Eye_Stroke2_Corner0_Rounded as EyeIcon} from '#/components/icons/Eye' +import {Play_Filled_Corner2_Rounded as PlayIcon} from '#/components/icons/Play' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' +import {type ExploreGalleryFocusProps} from './ExploreGallery' + +export function LivestreamCard({ + livestream, + width, + galleryFocus, +}: { + livestream: AtmosphereLivestreamCardData + width?: number + galleryFocus?: ExploreGalleryFocusProps +}) { + const {t: l} = useLingui() + const t = useTheme() + const moderationOpts = useModerationOpts() + const authorProfile = livestream.authorProfile + const moderation = + moderationOpts && authorProfile + ? moderateProfile(authorProfile, moderationOpts) + : undefined + const authorName = authorProfile + ? sanitizeDisplayName( + authorProfile.displayName || sanitizeHandle(authorProfile.handle), + moderation?.ui('displayName'), + ) + : undefined + + return ( + + + + + {livestream.image ? ( + + ) : undefined} + + + + + + {livestream.active ? ( + + + + + Live + + + {livestream.activeCount ? ( + + + + {livestream.activeCount} + + + ) : undefined} + + ) : undefined} + + + + {livestream.title} + + + + + {authorName} + + + + + + + ) +} diff --git a/src/screens/Atmosphere/components/PhotoCard.tsx b/src/screens/Atmosphere/components/PhotoCard.tsx new file mode 100644 index 000000000..7a3177da5 --- /dev/null +++ b/src/screens/Atmosphere/components/PhotoCard.tsx @@ -0,0 +1,132 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {moderateProfile} from '@bsky/sdk/moderation' +import {useLingui} from '@lingui/react/macro' + +import {sanitizeDisplayName} from '#/lib/strings/display-names' +import {sanitizeHandle} from '#/lib/strings/handles' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {formatCount} from '#/view/com/util/numeric/format' +import {UserAvatar} from '#/view/com/util/UserAvatar' +import {type AtmospherePhotoCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, useTheme, web} from '#/alf' +import {useInteractionState} from '#/components/hooks/useInteractionState' +import {Heart2_Stroke2_Corner0_Rounded as Heart} from '#/components/icons/Heart2' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' +import {type ExploreGalleryFocusProps} from './ExploreGallery' + +export function PhotoCard({ + photo, + galleryFocus, +}: { + photo: AtmospherePhotoCardData + galleryFocus?: ExploreGalleryFocusProps +}) { + const {t: l, i18n} = useLingui() + const t = useTheme() + const { + state: interacted, + onIn: onInteract, + onOut: onInteractOut, + } = useInteractionState() + const moderationOpts = useModerationOpts() + const moderation = moderationOpts + ? moderateProfile(photo.authorProfile, moderationOpts) + : undefined + const authorName = sanitizeDisplayName( + photo.authorProfile.displayName || + sanitizeHandle(photo.authorProfile.handle), + moderation?.ui('displayName'), + ) + + return ( + { + onInteract() + galleryFocus?.onFocus() + }} + onBlur={onInteractOut} + style={[a.flex_grow, a.w_full, a.flex_col, a.align_start, a.gap_sm]}> + + + {interacted ? ( + + ) : undefined} + {photo.likeCount > 0 ? ( + + + + {formatCount(i18n, photo.likeCount)} + + + ) : undefined} + + + {photo.title} + + + + + {authorName} + + + + ) +} diff --git a/src/screens/Atmosphere/components/PublicationCard.tsx b/src/screens/Atmosphere/components/PublicationCard.tsx new file mode 100644 index 000000000..022850fca --- /dev/null +++ b/src/screens/Atmosphere/components/PublicationCard.tsx @@ -0,0 +1,50 @@ +import {type AtmospherePublicationCardData} from '#/screens/Atmosphere/data/exploreData' +import {atoms as a, useTheme, utils} from '#/alf' +import {PublicationCard as SharedPublicationCard} from '#/components/Post/Embed/StandardSiteEmbed' +import type * as ssTypes from '#/components/Post/Embed/StandardSiteEmbed/types' +import {type ExploreGalleryFocusProps} from './ExploreGallery' + +export function PublicationCard({ + publication, + width, + galleryFocus, +}: { + publication: AtmospherePublicationCardData + width?: number + galleryFocus?: ExploreGalleryFocusProps +}) { + const t = useTheme() + const {accentRGB, accentForegroundRGB} = publication.view.source?.theme || {} + let themeColors: ssTypes.ThemeColors = { + custom: false, + accent: t.atoms.text.color, + accentForeground: t.atoms.text_inverted.color, + } + if (accentRGB && accentForegroundRGB) { + themeColors = { + custom: true, + accent: utils.rgbToHex(accentRGB.r, accentRGB.g, accentRGB.b), + accentForeground: utils.rgbToHex( + accentForegroundRGB.r, + accentForegroundRGB.g, + accentForegroundRGB.b, + ), + } + } + + return ( + + ) +} diff --git a/src/screens/Atmosphere/components/__tests__/ExploreGallery.test.tsx b/src/screens/Atmosphere/components/__tests__/ExploreGallery.test.tsx new file mode 100644 index 000000000..6731bb2b6 --- /dev/null +++ b/src/screens/Atmosphere/components/__tests__/ExploreGallery.test.tsx @@ -0,0 +1,204 @@ +import {useState} from 'react' +import { + Pressable, + ScrollView, + type StyleProp, + StyleSheet, + Text, + View, + type ViewStyle, +} from 'react-native' +import {fireEvent, render, screen} from '@testing-library/react-native' + +import {ExploreGallery, type ExploreGalleryFocusProps} from '../ExploreGallery' + +const mockEnv = {IS_WEB: false} + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: {message: string}) => value.message}), +})) +jest.mock('#/env', () => ({ + get IS_WEB() { + return mockEnv.IS_WEB + }, + IS_ANDROID: false, + IS_NATIVE: true, + IS_WEB_SAFARI: false, +})) +/* + * Each atom resolves to a marker naming itself, so tests can assert which + * atoms were applied without loading the whole design system. + */ +jest.mock('#/alf', () => ({ + atoms: new Proxy({}, {get: (_, name) => ({atom: name})}), + web: () => undefined, +})) +jest.mock('#/state/a11y', () => ({ + useA11y: () => ({screenReaderEnabled: false}), +})) +jest.mock('#/view/shell/BlockDrawerGesture', () => ({ + BlockDrawerGesture: ({children}: {children: React.ReactNode}) => children, +})) + +type Item = {id: string; title: string} + +const items: Item[] = [ + {id: 'a', title: 'Alpha'}, + {id: 'b', title: 'Beta'}, + {id: 'c', title: 'Gamma'}, +] + +function flat(style: unknown): ViewStyle { + return StyleSheet.flatten(style as StyleProp) ?? {} +} + +function slides() { + return screen.UNSAFE_root.findAll( + node => + typeof node.type === 'string' && + node.props['aria-roledescription'] === 'slide', + ) +} + +function FocusCard({ + item, + focusProps, +}: { + item: Item + focusProps: ExploreGalleryFocusProps +}) { + return ( + + ) +} + +function renderGallery(data: Item[] = items) { + return ( + ( + + )} + /> + ) +} + +beforeEach(() => { + mockEnv.IS_WEB = false +}) + +describe('ExploreGallery', () => { + it('renders one labelled slide per item inside a single root', () => { + render(renderGallery()) + + expect(screen.getAllByTestId('thingsGallery')).toHaveLength(1) + const rendered = slides() + expect(rendered).toHaveLength(3) + expect(rendered.map(slide => slide.props['aria-label'])).toEqual([ + 'Alpha', + 'Beta', + 'Gamma', + ]) + expect(screen.getAllByTestId(/^card-/)).toHaveLength(3) + }) + + it('keeps the bottom allowance inside each measured slide', () => { + render(renderGallery()) + + for (const slide of slides()) { + const [wrapper] = slide.children + if (typeof wrapper === 'string') throw new Error('expected an element') + expect(wrapper.props.style).toEqual([ + {atom: 'flex_grow'}, + {atom: 'pb_md'}, + ]) + } + const root = screen.getByTestId('thingsGallery') + expect(flat(root.props.style).height).toBeUndefined() + }) + + it('opts into stretch without imposing measured heights', () => { + render(renderGallery()) + + const scroll = screen.UNSAFE_getByType(ScrollView) + expect(flat(scroll.props.contentContainerStyle)).toMatchObject({ + atom: 'align_stretch', + }) + for (const slide of slides()) { + expect(flat(slide.props.style)).toMatchObject({atom: 'self_stretch'}) + fireEvent(slide, 'layout', { + nativeEvent: {layout: {x: 0, y: 0, width: 100, height: 200}}, + }) + } + expect( + flat(screen.getByTestId('thingsGallery').props.style).height, + ).toBeUndefined() + }) + + it('attaches focus to the rendered element rather than the slide', () => { + mockEnv.IS_WEB = true + render(renderGallery()) + + for (const slide of slides()) { + expect(slide.props.tabIndex).toBeUndefined() + } + expect(screen.getByTestId('card-a').props.tabIndex).toBe(0) + expect(screen.getByTestId('card-b').props.tabIndex).toBe(-1) + expect(screen.getByTestId('card-c').props.tabIndex).toBe(-1) + + fireEvent(screen.getByTestId('card-c'), 'focus') + expect(screen.getByTestId('card-a').props.tabIndex).toBe(-1) + expect(screen.getByTestId('card-c').props.tabIndex).toBe(0) + }) + + it('renders nothing for an empty list', () => { + render(renderGallery([])) + + expect(slides()).toHaveLength(0) + }) + + it('keys slides by id, not by array index', () => { + function Probe({item}: {item: Item}) { + // Remembers the title it first mounted with, so a stale index key shows + const [initial] = useState(item.title) + return ( + + {initial} + + ) + } + const gallery = (data: Item[]) => ( + } + /> + ) + const labels = () => + screen + .getAllByText(/^(Alpha|Beta|Gamma)$/) + .map(node => node.props.children) + + const {rerender} = render(gallery(items)) + expect(labels()).toEqual(['Alpha', 'Beta', 'Gamma']) + + rerender(gallery([items[2], items[0]])) + expect(labels()).toEqual(['Gamma', 'Alpha']) + expect(slides().map(slide => slide.props['aria-label'])).toEqual([ + 'Gamma', + 'Alpha', + ]) + }) +}) diff --git a/src/screens/Atmosphere/components/__tests__/ExploreSectionHeader.test.tsx b/src/screens/Atmosphere/components/__tests__/ExploreSectionHeader.test.tsx new file mode 100644 index 000000000..5ed5adb32 --- /dev/null +++ b/src/screens/Atmosphere/components/__tests__/ExploreSectionHeader.test.tsx @@ -0,0 +1,20 @@ +import {render, screen} from '@testing-library/react-native' + +import {ExploreSectionHeader} from '../ExploreSectionHeader' + +jest.mock('#/alf', () => ({ + atoms: {text_lg: {}, font_semi_bold: {}}, +})) +jest.mock('#/components/Typography', () => { + const {Text} = + jest.requireActual('react-native') + return {Text} +}) + +it('renders an accessible section heading without a see-more link', () => { + render() + + expect(screen.getByRole('header', {name: 'Featured articles'})).toBeTruthy() + expect(screen.queryByText('See more')).toBeNull() + expect(screen.queryByRole('link')).toBeNull() +}) diff --git a/src/screens/Atmosphere/components/__tests__/FeaturedSections.test.tsx b/src/screens/Atmosphere/components/__tests__/FeaturedSections.test.tsx new file mode 100644 index 000000000..7d6f368bb --- /dev/null +++ b/src/screens/Atmosphere/components/__tests__/FeaturedSections.test.tsx @@ -0,0 +1,249 @@ +import {type StyleProp, StyleSheet, type ViewStyle} from 'react-native' +import {render, screen} from '@testing-library/react-native' + +import { + type AtmosphereArticleCardData, + type AtmosphereLivestreamCardData, + type AtmospherePhotoCardData, + type AtmospherePublicationCardData, +} from '#/screens/Atmosphere/data/exploreData' +import {type ExploreGalleryFocusProps} from '../ExploreGallery' +import {FeaturedArticles} from '../FeaturedArticles' +import {FeaturedLivestreams} from '../FeaturedLivestreams' +import {FeaturedPhotos} from '../FeaturedPhotos' +import {FeaturedPublications} from '../FeaturedPublications' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: {message: string}) => value.message}), +})) +jest.mock('#/env', () => ({ + IS_WEB: true, + IS_ANDROID: false, + IS_NATIVE: true, + IS_WEB_SAFARI: false, +})) +jest.mock('#/state/a11y', () => ({ + useA11y: () => ({screenReaderEnabled: false}), +})) +jest.mock('#/view/shell/BlockDrawerGesture', () => ({ + BlockDrawerGesture: ({children}: {children: React.ReactNode}) => children, +})) +jest.mock('#/alf', () => ({ + atoms: new Proxy({}, {get: () => ({})}), + web: () => undefined, +})) + +jest.mock('../ExploreSectionHeader', () => { + const {Text: MockText} = + jest.requireActual('react-native') + return { + ExploreSectionHeader: ({title}: {title: string}) => ( + {title} + ), + } +}) + +/* + * The cards expose the props the sections hand them, and a focus target that + * is wired up the way the real cards wire their Link. + */ +function mockCard(prefix: string, prop: string) { + const {Pressable} = + jest.requireActual('react-native') + return ({ + width, + galleryFocus, + ...rest + }: Record & { + width?: number + galleryFocus?: ExploreGalleryFocusProps + }) => { + const item = rest[prop] as {id: string; title: string} + return ( + + ) + } +} +jest.mock('../ArticleCard', () => ({ + ArticleCard: mockCard('article', 'article'), +})) +jest.mock('../LivestreamCard', () => ({ + LivestreamCard: mockCard('livestream', 'livestream'), +})) +jest.mock('../PublicationCard', () => ({ + PublicationCard: mockCard('publication', 'publication'), +})) +jest.mock('../PhotoCard', () => ({PhotoCard: mockCard('photo', 'photo')})) + +const articles = [ + {id: 'a1', title: 'First article'}, + {id: 'a2', title: 'Second article'}, +] as AtmosphereArticleCardData[] +const livestreams = [ + {id: 'l1', title: 'First stream'}, + {id: 'l2', title: 'Second stream'}, +] as AtmosphereLivestreamCardData[] +const photos = [ + {id: 'p1', title: 'First photo'}, + {id: 'p2', title: 'Second photo'}, +] as AtmospherePhotoCardData[] + +const publications = [ + {id: 'u1', title: 'First publication'}, + {id: 'u2', title: 'Second publication'}, +] as AtmospherePublicationCardData[] + +function slides() { + return screen.UNSAFE_root.findAll( + node => + typeof node.type === 'string' && + node.props['aria-roledescription'] === 'slide', + ) +} + +function flat(style: unknown): ViewStyle { + return StyleSheet.flatten(style as StyleProp) ?? {} +} + +function width(testID: string) { + return flat(screen.getByTestId(testID).props.style).width +} + +describe('FeaturedArticles', () => { + it('renders the header and one slide per article in a labelled gallery', () => { + render() + + expect(screen.getByText('Featured articles')).toBeTruthy() + expect(screen.getByTestId('atmosphereArticlesGallery')).toBeTruthy() + expect(slides().map(slide => slide.props['aria-label'])).toEqual([ + 'First article', + 'Second article', + ]) + expect(width('article-a1')).toBe(250) + expect(width('article-a2')).toBe(250) + }) + + it('wires the gallery focus target to each card', () => { + render() + + expect(screen.getByTestId('article-a1').props.tabIndex).toBe(0) + expect(screen.getByTestId('article-a2').props.tabIndex).toBe(-1) + for (const slide of slides()) { + expect(slide.props.tabIndex).toBeUndefined() + } + }) + + it('renders nothing, including the header, without articles', () => { + render() + + expect(screen.queryByText('Featured articles')).toBeNull() + expect(screen.queryByTestId('atmosphereArticlesGallery')).toBeNull() + }) +}) + +describe('FeaturedLivestreams', () => { + it('renders the header and one slide per livestream in a labelled gallery', () => { + render() + + expect(screen.getByText('Featured livestreams')).toBeTruthy() + expect(screen.getByTestId('atmosphereLivestreamsGallery')).toBeTruthy() + expect(slides().map(slide => slide.props['aria-label'])).toEqual([ + 'First stream', + 'Second stream', + ]) + expect(width('livestream-l1')).toBe(214) + expect(width('livestream-l2')).toBe(214) + }) + + it('wires the gallery focus target to each card', () => { + render() + + expect(screen.getByTestId('livestream-l1').props.tabIndex).toBe(0) + expect(screen.getByTestId('livestream-l2').props.tabIndex).toBe(-1) + }) + + it('renders nothing, including the header, without livestreams', () => { + render() + + expect(screen.queryByText('Featured livestreams')).toBeNull() + expect(screen.queryByTestId('atmosphereLivestreamsGallery')).toBeNull() + }) +}) + +describe('FeaturedPhotos', () => { + it('renders the header and one slide per photo in a labelled gallery', () => { + render() + + expect(screen.getByText('Featured photos')).toBeTruthy() + expect(screen.getByTestId('atmospherePhotosGallery')).toBeTruthy() + expect(slides().map(slide => slide.props['aria-label'])).toEqual([ + 'First photo', + 'Second photo', + ]) + }) + + it('keeps the card inside a 225px wrapper', () => { + render() + + for (const id of ['p1', 'p2']) { + // The card itself is unsized; the nearest sized ancestor is the wrapper + let node = screen.getByTestId(`photo-${id}`).parent + while (node && flat(node.props.style).width == null) { + node = node.parent + } + expect(flat(node?.props.style).width).toBe(225) + } + }) + + it('wires the gallery focus target to each card', () => { + render() + + expect(screen.getByTestId('photo-p1').props.tabIndex).toBe(0) + expect(screen.getByTestId('photo-p2').props.tabIndex).toBe(-1) + }) + + it('renders nothing, including the header, without photos', () => { + render() + + expect(screen.queryByText('Featured photos')).toBeNull() + expect(screen.queryByTestId('atmospherePhotosGallery')).toBeNull() + }) +}) + +describe('FeaturedPublications', () => { + it('renders the header and one slide per publication in a labelled gallery', () => { + render() + + expect(screen.getByText('Featured publications')).toBeTruthy() + expect(screen.getByTestId('atmospherePublicationsGallery')).toBeTruthy() + expect(slides().map(slide => slide.props['aria-label'])).toEqual([ + 'First publication', + 'Second publication', + ]) + expect(width('publication-u1')).toBe(320) + expect(width('publication-u2')).toBe(320) + }) + + it('wires the gallery focus target to each card', () => { + render() + + expect(screen.getByTestId('publication-u1').props.tabIndex).toBe(0) + expect(screen.getByTestId('publication-u2').props.tabIndex).toBe(-1) + }) + + it('renders nothing, including the header, without publications', () => { + render() + + expect(screen.queryByText('Featured publications')).toBeNull() + expect(screen.queryByTestId('atmospherePublicationsGallery')).toBeNull() + }) +}) diff --git a/src/screens/Atmosphere/components/__tests__/PublicationCard.test.tsx b/src/screens/Atmosphere/components/__tests__/PublicationCard.test.tsx new file mode 100644 index 000000000..ce01e4778 --- /dev/null +++ b/src/screens/Atmosphere/components/__tests__/PublicationCard.test.tsx @@ -0,0 +1,251 @@ +import {Children} from 'react' +import {StyleSheet, View} from 'react-native' +import {fireEvent, render, screen} from '@testing-library/react-native' + +import {type AtmospherePublicationCardData} from '#/screens/Atmosphere/data/exploreData' +import {PublicationCard} from '../PublicationCard' + +const mockBreakpoints = {gtPhone: true} + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: {message: string}) => value.message}), +})) +jest.mock('#/alf', () => { + const atoms = new Proxy( + {}, + {get: (_, name) => (name === 'flex_grow' ? {flexGrow: 1} : {})}, + ) + return { + atoms, + web: () => undefined, + utils: jest.requireActual( + '#/alf/util/colorGeneration', + ), + useBreakpoints: () => mockBreakpoints, + useTheme: () => ({ + atoms: new Proxy( + {}, + {get: (_, name) => ({color: `theme-${String(name)}`})}, + ), + }), + } +}) +jest.mock('#/env', () => ({IS_NATIVE: false})) +jest.mock('#/analytics', () => ({useAnalytics: () => ({metric: jest.fn()})})) +jest.mock('#/lib/haptics', () => ({ + useHaptics: () => ({tap: jest.fn(), longPress: jest.fn()}), +})) +jest.mock('#/lib/sharing', () => ({shareUrl: jest.fn()})) +jest.mock('#/view/com/util/UserAvatar', () => ({ + UserAvatar: ({avatar}: {avatar?: string}) => { + const {Text} = + jest.requireActual('react-native') + return {avatar} + }, +})) +jest.mock('#/components/MediaInsetBorder', () => ({ + MediaInsetBorder: () => null, +})) +jest.mock('#/components/Divider', () => ({Divider: () => null})) +jest.mock('#/components/Button', () => ({ + ButtonIcon: () => null, + ButtonText: ({children}: {children: React.ReactNode}) => children, +})) +jest.mock('#/components/Typography', () => { + const {Text} = + jest.requireActual('react-native') + return {Text} +}) +jest.mock('#/components/icons/Arrow', () => ({ + ArrowTopRight_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/Clock', () => ({ + Clock_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/community/StandardSite', () => ({ + StandardSite: () => null, +})) +jest.mock( + '#/components/Post/Embed/StandardSiteEmbed/StandardSiteMetaRow', + () => ({StandardSiteMetaRow: () => null}), +) +jest.mock( + '#/components/Post/Embed/StandardSiteEmbed/StandardSiteThemeProvider', + () => ({ + StandardSiteThemeProvider: ({children}: {children: React.ReactNode}) => + children, + }), +) + +/* + * A stand-in for Link that keeps the props under test on a single host + * element. The shared card and its subscribe button render through it. + */ +jest.mock('#/components/Link', () => { + const {Pressable: HostPressable} = + jest.requireActual('react-native') + return { + Link: ({ + children, + label, + to, + ref, + tabIndex, + onFocus, + }: { + children: React.ReactNode + label: string + to: string + ref?: React.Ref + tabIndex?: number + onFocus?: (e: unknown) => void + }) => ( + + {typeof children === 'function' ? null : children} + + ), + } +}) + +const publication: AtmospherePublicationCardData = { + id: 'https://example.com/pub', + title: 'Test publication', + view: { + uri: 'https://example.com/pub', + title: 'Test publication', + description: 'A description', + source: { + uri: 'https://example.com/pub', + title: 'Test publication', + icon: 'https://example.com/logo.png', + theme: { + accentRGB: {r: 18, g: 52, b: 86}, + accentForegroundRGB: {r: 255, g: 255, b: 255}, + }, + }, + }, +} + +function links() { + return screen.getAllByRole('link') +} + +function focusProps(tabIndex: 0 | -1 | undefined) { + return {focusRef: jest.fn(), tabIndex, onFocus: jest.fn()} +} + +beforeEach(() => { + mockBreakpoints.gtPhone = true +}) + +describe.each([true, false])('PublicationCard (gtPhone: %s)', gtPhone => { + /* The Atmosphere card hides the CTA on wide layouts (`hideSubscribe`). */ + const linkCount = gtPhone ? 1 : 2 + + beforeEach(() => { + mockBreakpoints.gtPhone = gtPhone + }) + + it('lets the shared card fill a stretched slide while keeping its width', () => { + render() + expect(StyleSheet.flatten(screen.root.props.style)).toMatchObject({ + flexGrow: 1, + width: 320, + }) + }) + + it('renders the primary link and the call to action', () => { + render() + + expect(links()).toHaveLength(linkCount) + for (const link of links()) { + expect(link.props.accessibilityValue).toEqual({ + text: 'https://example.com/pub', + }) + } + expect(screen.getByTestId('logo').props.children).toBe( + 'https://example.com/logo.png', + ) + expect(screen.getByText('A description')).toBeTruthy() + }) + + it.each([0, -1, undefined] as const)( + 'gives both links tabIndex %s and only the primary link the ref', + tabIndex => { + const focus = focusProps(tabIndex) + render() + + for (const link of links()) { + expect(link.props.tabIndex).toBe(tabIndex) + } + expect(focus.focusRef).toHaveBeenCalledTimes(1) + expect(focus.focusRef).toHaveBeenCalledWith(expect.anything()) + }, + ) + + it('composes focus on both links with the gallery callback', () => { + const focus = focusProps(-1) + render() + + for (const link of links()) fireEvent(link, 'focus') + + expect(focus.onFocus).toHaveBeenCalledTimes(linkCount) + }) + + it('renders without gallery focus props', () => { + render() + + for (const link of links()) { + expect(link.props.tabIndex).toBeUndefined() + expect(() => fireEvent(link, 'focus')).not.toThrow() + } + }) + + it('does not render a raw text node for an empty description', () => { + render( + , + ) + + /* + * Inspect the supplied children: the native test renderer can drop empty + * strings from its output, while React Native Web checks props directly. + */ + const rawTextNodes = screen + .UNSAFE_getAllByType(View) + .flatMap(view => Children.toArray(view.props.children)) + .filter(child => typeof child === 'string' || typeof child === 'number') + expect(rawTextNodes).toEqual([]) + }) + + it('falls back to an initial when there is no logo or theme', () => { + const {source, ...view} = publication.view + render( + , + ) + + expect(screen.queryByTestId('logo')).toBeNull() + expect(screen.getByText('T')).toBeTruthy() + expect(links()).toHaveLength(linkCount) + }) +}) diff --git a/src/screens/Atmosphere/components/__tests__/galleryFocus.test.tsx b/src/screens/Atmosphere/components/__tests__/galleryFocus.test.tsx new file mode 100644 index 000000000..15ccfcc17 --- /dev/null +++ b/src/screens/Atmosphere/components/__tests__/galleryFocus.test.tsx @@ -0,0 +1,246 @@ +import {StyleSheet} from 'react-native' +import {fireEvent, render, screen} from '@testing-library/react-native' + +import { + type AtmosphereArticleCardData, + type AtmosphereLivestreamCardData, + type AtmospherePhotoCardData, +} from '#/screens/Atmosphere/data/exploreData' +import {ArticleCard} from '../ArticleCard' +import {type ExploreGalleryFocusProps} from '../ExploreGallery' +import {LivestreamCard} from '../LivestreamCard' +import {PhotoCard} from '../PhotoCard' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: (value: {message: string}) => value.message, + i18n: {number: String}, + }), +})) +jest.mock('#/alf', () => { + const atoms = new Proxy( + {}, + {get: (_, name) => (name === 'flex_grow' ? {flexGrow: 1} : {})}, + ) + const themeAtoms = new Proxy( + { + bg: {backgroundColor: '#ffffff'}, + bg_contrast_25: {backgroundColor: '#f8f8f8'}, + border_contrast_low: {borderColor: '#dddddd'}, + border_contrast_high: {borderColor: '#555555'}, + }, + {get: (target, name) => target[name as keyof typeof target] ?? {}}, + ) + return { + atoms, + web: (props: Record) => props, + useTheme: () => ({ + atoms: themeAtoms, + palette: new Proxy({}, {get: () => ''}), + }), + } +}) +jest.mock('#/components/Typography', () => { + const {Text} = + jest.requireActual('react-native') + return {Text} +}) +jest.mock('expo-image', () => { + const {View} = + jest.requireActual('react-native') + return {Image: View} +}) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => undefined, +})) +jest.mock('#/view/com/util/UserAvatar', () => ({UserAvatar: () => null})) +jest.mock('#/view/com/util/numeric/format', () => ({formatCount: String})) +jest.mock('#/components/icons/Heart2', () => ({ + Heart2_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/Eye', () => ({ + Eye_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/Play', () => ({ + Play_Filled_Corner2_Rounded: () => null, +})) + +/* + * The real Link is the only interactive element in each card. This stand-in + * keeps the props the cards give it and renders them on a single host element. + */ +jest.mock('#/components/Link', () => { + const {Pressable} = + jest.requireActual('react-native') + return { + Link: ({ + children, + label, + to, + ref, + tabIndex, + onFocus, + onBlur, + onMouseEnter, + onMouseLeave, + style, + }: { + children: React.ReactNode + label: string + to: string + ref?: React.Ref + tabIndex?: number + onFocus?: () => void + onBlur?: () => void + onMouseEnter?: () => void + onMouseLeave?: () => void + style?: React.ComponentProps['style'] + }) => ( + + {children} + + ), + } +}) + +const authorProfile = { + did: 'did:plc:author', + handle: 'author.test', + displayName: 'Author', +} as AtmospherePhotoCardData['authorProfile'] + +const article: AtmosphereArticleCardData = { + id: 'article', + href: '/article', + title: 'An article', +} +const livestream: AtmosphereLivestreamCardData = { + id: 'livestream', + href: '/livestream', + title: 'A livestream', + active: false, + authorProfile, +} +const photo: AtmospherePhotoCardData = { + id: 'photo', + href: '/photo', + title: 'A photo', + image: 'https://example.com/photo.jpg', + likeCount: 0, + authorProfile, +} + +const cards: [ + string, + (focus?: ExploreGalleryFocusProps) => React.ReactElement, +][] = [ + [ + 'ArticleCard', + focus => , + ], + [ + 'LivestreamCard', + focus => , + ], + ['PhotoCard', focus => ], +] + +describe.each(cards)('%s gallery focus', (_name, renderCard) => { + it('lets the card root fill a stretched slide', () => { + render(renderCard()) + expect(StyleSheet.flatten(screen.root.props.style)).toMatchObject({ + flexGrow: 1, + }) + }) + + it('attaches the focus props to its single Link', () => { + const galleryFocus = { + focusRef: jest.fn(), + tabIndex: 0 as const, + onFocus: jest.fn(), + } + render(renderCard(galleryFocus)) + + const link = screen.getByTestId('link') + expect(screen.getAllByRole('link')).toHaveLength(1) + expect(galleryFocus.focusRef).toHaveBeenCalledWith(expect.anything()) + expect(link.props.tabIndex).toBe(0) + + fireEvent(link, 'focus') + expect(galleryFocus.onFocus).toHaveBeenCalledTimes(1) + }) + + it('passes a roving tabIndex of -1 through', () => { + render(renderCard({focusRef: jest.fn(), tabIndex: -1, onFocus: jest.fn()})) + + expect(screen.getByTestId('link').props.tabIndex).toBe(-1) + }) + + it('renders as before without gallery focus props', () => { + render(renderCard()) + + const link = screen.getByTestId('link') + expect(link.props.tabIndex).toBeUndefined() + expect(() => fireEvent(link, 'focus')).not.toThrow() + expect(link.props.accessibilityLabel).toMatch(/^Open/) + }) +}) + +const interactions = [ + ['hover', 'mouseEnter', 'mouseLeave'], + ['focus', 'focus', 'blur'], +] + +it.each(interactions)( + 'highlights the article background and border on %s', + (_name, enter, leave) => { + render() + const link = screen.getByTestId('link') + const card = screen.root + + expect(card).toHaveStyle({ + backgroundColor: '#ffffff', + borderColor: '#dddddd', + }) + fireEvent(link, enter) + expect(card).toHaveStyle({ + backgroundColor: '#f8f8f8', + borderColor: '#555555', + }) + fireEvent(link, leave) + expect(card).toHaveStyle({ + backgroundColor: '#ffffff', + borderColor: '#dddddd', + }) + }, +) + +it.each(interactions)( + 'dims the photo image on %s without intercepting interactions', + (_name, enter, leave) => { + render() + const link = screen.getByTestId('link') + + expect(screen.queryByTestId('atmospherePhotoHoverOverlay')).toBeNull() + fireEvent(link, enter) + const overlay = screen.getByTestId('atmospherePhotoHoverOverlay') + expect(overlay).toHaveStyle({backgroundColor: 'rgba(0, 0, 0, 0.1)'}) + expect(overlay.props.pointerEvents).toBe('none') + expect(overlay.props.accessible).toBe(false) + expect(screen.getByText(photo.title)).toBeTruthy() + + fireEvent(link, leave) + expect(screen.queryByTestId('atmospherePhotoHoverOverlay')).toBeNull() + }, +) diff --git a/src/screens/Atmosphere/data/__tests__/exploreData.test.ts b/src/screens/Atmosphere/data/__tests__/exploreData.test.ts new file mode 100644 index 000000000..1331d8ac4 --- /dev/null +++ b/src/screens/Atmosphere/data/__tests__/exploreData.test.ts @@ -0,0 +1,715 @@ +import {exploreResponseFixture} from '#/screens/Atmosphere/__tests__/fixtures/exploreResponse' +import {livestreamPreviewFixture} from '#/screens/Atmosphere/__tests__/fixtures/livestreamPreview' +import { + type AtmosphereData, + getAtmosphereAnnouncementBanner, + getAtmosphereApps, + getAtmosphereArticles, + getAtmosphereLivestreams, + getAtmospherePhotos, + getAtmospherePublications, +} from '#/screens/Atmosphere/data/exploreData' +import {app} from '#/lexicons' + +function parseData(data: unknown): AtmosphereData { + return app.bsky.unspecced.getAtmosphereExploreTab.$output.schema.parse(data) +} + +const fixtureData = parseData(exploreResponseFixture) + +const emptyData: AtmosphereData = { + articles: {items: []}, + publications: {items: []}, + photos: {items: []}, + livestreams: {items: []}, + apps: [], +} + +const testProfile = { + $type: 'app.bsky.actor.defs#profileViewBasic', + did: 'did:plc:6ayddqghxhciedbaofoxkcbs', + handle: 'test.bsky.social', +} + +const image = { + $type: 'app.bsky.embed.external#viewGalleryImage', + thumbnail: 'https://example.com/thumbnail.jpg', + fullsize: 'https://example.com/fullsize.jpg', +} + +describe('Atmosphere Explore response fixtures', () => { + it('validates a populated synthetic response with nested view metadata', () => { + expect(fixtureData).toEqual(exploreResponseFixture) + expect(fixtureData.articles.items[0].view.publisher).toMatchObject({ + $type: 'app.bsky.embed.external#viewArticlePublication', + logo: 'https://example.com/logo.jpg', + theme: { + background: '#ffffff', + foreground: '#000000', + accent: '#123456', + accentForeground: '#ffffff', + }, + }) + expect(fixtureData.publications.items[0].view.subscriptionCount).toBe(1) + expect(fixtureData.photos.items[0].view.items[0].$type).toBe( + 'app.bsky.embed.external#viewGalleryImage', + ) + }) + + it.each(['articles', 'publications', 'photos', 'livestreams'] as const)( + 'validates the %s list envelope and string recommendation ID', + section => { + const recIdStr = '18446744073709551615' + expect(parseData(emptyData)[section]).toEqual({items: []}) + expect( + parseData({...emptyData, [section]: {items: [], recIdStr}})[section], + ).toEqual({items: [], recIdStr}) + expect(() => parseData({...emptyData, [section]: []})).toThrow() + expect(() => parseData({...emptyData, [section]: {}})).toThrow() + expect(() => parseData({...emptyData, [section]: undefined})).toThrow() + expect(() => + parseData({...emptyData, [section]: {items: [], recIdStr: 123}}), + ).toThrow() + }, + ) + + it('keeps algorithmic and curated articles and recommendation metadata', () => { + const items = [...fixtureData.articles.items] + .reverse() + .map((item, index) => ({ + ...item, + featured: index !== 0, + })) + const data = parseData({ + ...fixtureData, + articles: {items, recIdStr: '18446744073709551615'}, + }) + + expect(data.articles.recIdStr).toBe('18446744073709551615') + expect(getAtmosphereArticles(data).map(article => article.href)).toEqual([ + 'https://example.com/first-article', + 'https://example.com/second-article', + ]) + expect(data.articles.items.map(item => item.featured)).toEqual([ + false, + true, + ]) + }) + + it.each([ + { + schema: app.bsky.embed.external.viewArticle, + view: fixtureData.articles.items[0].view, + }, + { + schema: app.bsky.embed.external.viewArticlePublication, + view: fixtureData.publications.items[0].view, + }, + { + schema: app.bsky.embed.external.viewGallery, + view: fixtureData.photos.items[0].view, + }, + { + schema: app.bsky.embed.external.viewLivestream, + view: livestreamPreviewFixture[0].view, + }, + ])('uses generated validation for $view.$type', ({schema, view}) => { + expect(schema.parse(view)).toMatchObject(view) + expect(() => schema.parse({...view, uri: 'invalid'})).toThrow() + expect(() => + schema.parse({...view, associatedProfiles: [{did: 'nope'}]}), + ).toThrow() + }) + + it('validates gallery images and skips malformed images at the adapter boundary', () => { + expect(app.bsky.embed.external.viewGalleryImage.parse(image)).toMatchObject( + image, + ) + expect(() => + app.bsky.embed.external.viewGalleryImage.parse({ + ...image, + thumbnail: 'invalid', + }), + ).toThrow() + const photo = fixtureData.photos.items[0] + expect( + getAtmospherePhotos({ + ...fixtureData, + photos: { + items: [ + { + ...photo, + view: { + ...photo.view, + items: [{...image, thumbnail: 'invalid'} as never], + }, + }, + ], + }, + }), + ).toEqual([]) + }) + + it.each(['articles', 'publications'] as const)( + 'sorts %s by description length without mutating the response', + section => { + const item = fixtureData[section].items[0] + const descriptions = [ + '', + 'Short', + ' \n\t '.repeat(10), + 'The longest description in this list.', + 'Other', + ' Tiny ', + '', + ] + const data = parseData({ + ...emptyData, + [section]: { + recIdStr: '42', + items: descriptions.map((description, index) => ({ + ...item, + featured: index !== 3, + view: { + ...item.view, + uri: `https://example.com/${index}`, + description, + }, + })), + }, + }) + const before = JSON.stringify(data) + Object.freeze(data[section].items) + + const cards = + section === 'articles' + ? getAtmosphereArticles(data) + : getAtmospherePublications(data) + + expect(cards.map(card => card.id)).toEqual( + [3, 1, 4, 5, 0, 2, 6].map(index => `https://example.com/${index}`), + ) + expect(JSON.stringify(data)).toBe(before) + expect(data[section].recIdStr).toBe('42') + }, + ) + + it('sorts articles with images first, then by description length', () => { + const item = fixtureData.articles.items[0] + const entries = [ + {description: 'The longest description. '.repeat(10)}, + {description: 'Short', image: 'https://example.com/short.jpg'}, + {description: '', image: 'https://example.com/empty.jpg'}, + { + description: 'An image article with a longer description', + image: 'https://example.com/long.jpg', + }, + {description: 'Tiny'}, + {description: 'Medium text', image: 'https://example.com/medium.jpg'}, + ] + const data = parseData({ + ...emptyData, + articles: { + items: entries.map(({description, image}, index) => ({ + ...item, + view: { + ...item.view, + uri: `https://example.com/${index}`, + description, + image, + }, + })), + }, + }) + const before = JSON.stringify(data) + Object.freeze(data.articles.items) + + expect(getAtmosphereArticles(data).map(article => article.id)).toEqual( + [3, 5, 1, 2, 0, 4].map(index => `https://example.com/${index}`), + ) + expect(JSON.stringify(data)).toBe(before) + }) + + it('maps populated card fields and prioritizes article images', () => { + const articles = getAtmosphereArticles(fixtureData) + expect( + articles.map(({title, publisher, description}) => ({ + title, + publisher, + description, + })), + ).toEqual([ + { + title: 'First article', + publisher: 'Test publication', + description: undefined, + }, + { + title: 'Second article', + publisher: 'Test publication', + description: 'An article description', + }, + ]) + expect(articles[0]).toMatchObject({ + id: 'https://example.com/first-article', + href: 'https://example.com/first-article', + image: 'https://example.com/article.jpg', + publisherAvatar: 'https://example.com/logo.jpg', + }) + + const photos = getAtmospherePhotos(fixtureData) + expect(photos.map(({title}) => title)).toEqual([ + 'First photo', + 'Second photo', + ]) + expect(photos[0]).toMatchObject({ + id: 'https://example.com/gallery-0', + href: 'https://example.com/gallery-0', + image: 'https://example.com/thumbnail.jpg', + imageAlt: 'A test photo', + likeCount: 2, + authorProfile: {handle: 'author.test'}, + }) + + expect(getAtmosphereApps(fixtureData)).toEqual([ + { + id: 'app', + title: 'Test app', + description: 'An app description', + logo: 'https://example.com/app-logo.jpg', + backgroundImage: 'https://example.com/app-background.jpg', + overlayColor: '#123456', + textColor: '#ffffff', + href: 'https://example.com/app', + }, + ]) + expect(getAtmosphereAnnouncementBanner(fixtureData)).toEqual({ + id: 'banner', + title: 'Test announcement', + description: 'An announcement description', + image: 'https://example.com/banner.jpg', + overlayColor: '#000000', + textColor: '#ffffff', + href: 'https://example.com/announcement', + }) + }) + + describe('getAtmospherePublications', () => { + const publicationView = fixtureData.publications.items[0].view + const withPublications = ( + items: {featured: boolean; view: typeof publicationView}[], + ) => parseData({...emptyData, publications: {items, recIdStr: '1'}}) + + it('returns nothing for an empty list', () => { + expect(getAtmospherePublications(emptyData)).toEqual([]) + }) + + it('keeps response order for equal-length descriptions, regardless of featured', () => { + const data = withPublications([ + {featured: false, view: {...publicationView, uri: 'https://a.test/'}}, + {featured: true, view: {...publicationView, uri: 'https://b.test/'}}, + {featured: false, view: {...publicationView, uri: 'https://c.test/'}}, + ]) + + expect(getAtmospherePublications(data).map(p => p.id)).toEqual([ + 'https://a.test/', + 'https://b.test/', + 'https://c.test/', + ]) + }) + + it('builds the legacy view the shared card renders', () => { + const [card] = getAtmospherePublications(fixtureData) + + expect(card).toMatchObject({ + id: publicationView.uri, + title: publicationView.title, + view: { + uri: publicationView.uri, + title: publicationView.title, + description: publicationView.description, + associatedProfiles: publicationView.associatedProfiles, + source: { + uri: publicationView.uri, + title: publicationView.title, + icon: publicationView.logo, + theme: { + backgroundRGB: {r: 255, g: 255, b: 255}, + foregroundRGB: {r: 0, g: 0, b: 0}, + accentRGB: {r: 0x12, g: 0x34, b: 0x56}, + accentForegroundRGB: {r: 255, g: 255, b: 255}, + }, + }, + }, + }) + }) + + it('copies associated metadata and does not mutate the response', () => { + /* Built without parsing: only the shape of the refs matters here. */ + const data: AtmosphereData = { + ...emptyData, + publications: { + recIdStr: '1', + items: [ + { + featured: true, + view: { + ...publicationView, + associatedRefs: [ + { + uri: 'at://did:plc:6ayddqghxhciedbaofoxkcbs/site.standard.publication/1', + cid: 'bafyreiaxduxpwdpjgvve3klfs4flkwjwfqiurszw4o6jvjarpqqmeqwiza', + }, + ], + }, + }, + ], + }, + } + const before = JSON.stringify(data) + const [card] = getAtmospherePublications(data) + + expect(card.view.associatedRefs).toEqual( + data.publications.items[0].view.associatedRefs, + ) + expect(JSON.stringify(data)).toBe(before) + expect(data.publications.recIdStr).toBe('1') + }) + + it.each([ + { + name: 'partial', + theme: {accent: '#fff'}, + expected: {accentRGB: {r: 255, g: 255, b: 255}}, + }, + { + name: 'invalid', + theme: {accent: 'red', background: '#12'}, + expected: {}, + }, + ])('converts $name theme colors', ({theme, expected}) => { + const data = withPublications([ + {featured: true, view: {...publicationView, theme}}, + ]) + const source = getAtmospherePublications(data)[0].view.source + + expect(source?.theme).toMatchObject(expected) + for (const key of [ + 'backgroundRGB', + 'foregroundRGB', + 'accentRGB', + 'accentForegroundRGB', + ] as const) { + if (!(key in expected)) expect(source?.theme?.[key]).toBeUndefined() + } + }) + + it('keeps publications without a logo, theme, or profiles', () => { + const {logo, theme, subscribers, ...bare} = publicationView + const data = withPublications([{featured: false, view: bare}]) + const [card] = getAtmospherePublications(data) + + expect(card.view.source?.icon).toBeUndefined() + expect(card.view.source?.theme).toBeUndefined() + expect(card.view.associatedProfiles).toBeUndefined() + }) + }) + + describe('dedupes items by id', () => { + const [article] = fixtureData.articles.items + const [photo] = fixtureData.photos.items + const [livestream] = parseData({ + ...emptyData, + livestreams: {items: livestreamPreviewFixture}, + }).livestreams.items + const [publication] = fixtureData.publications.items + const [firstApp] = fixtureData.apps + + function twoOf(item: T) { + return { + first: item, + second: {...item, view: {...item.view, uri: 'https://other.test/'}}, + } + } + + it.each([ + ['articles', article, getAtmosphereArticles], + ['publications', publication, getAtmospherePublications], + ['photos', photo, getAtmospherePhotos], + ['livestreams', livestream, getAtmosphereLivestreams], + ] as const)('in %s, keeping the first occurrence', (name, item, adapt) => { + const {first, second} = twoOf(item) + const duplicate = { + ...first, + view: {...first.view, title: 'duplicate'}, + } + const data = { + ...emptyData, + [name]: {items: [first, second, duplicate]}, + } + + const result = adapt(data) + + expect(result).toHaveLength(2) + expect(result.map(r => r.id).sort()).toEqual( + [first.view.uri, second.view.uri].sort(), + ) + expect(result.map(r => r.title)).not.toContain('duplicate') + }) + + it('in apps, keeping the first occurrence', () => { + const data = { + ...emptyData, + apps: [ + firstApp, + {...firstApp, id: 'other'}, + {...firstApp, title: 'dupe'}, + ], + } satisfies AtmosphereData + + const result = getAtmosphereApps(data) + + expect(result.map(r => r.id)).toEqual([firstApp.id, 'other']) + expect(result[0].title).toBe(firstApp.title) + }) + }) + + it('adapts the active and ended local livestream previews', () => { + const previewData = parseData({ + ...emptyData, + livestreams: {items: livestreamPreviewFixture}, + }) + const livestreams = getAtmosphereLivestreams(previewData) + + expect( + livestreams.map(({title, active, href}) => ({ + title, + active, + href, + })), + ).toEqual([ + { + title: 'A look at open publishing', + active: true, + href: 'https://example.com/livestreams/open-publishing', + }, + { + title: 'Community Q&A', + active: false, + href: 'https://example.com/livestreams/community-q-and-a', + }, + { + title: 'Creative coding session', + active: true, + href: 'https://example.com/livestreams/creative-coding', + }, + ]) + expect( + livestreamPreviewFixture.every( + item => + item.featured && + item.view.$type === 'app.bsky.embed.external#viewLivestream', + ), + ).toBe(true) + expect(livestreams[0].image).toBe(livestreamPreviewFixture[0].view.image) + }) + + it('safely handles absent optional data, empty arrays, and gallery variants', () => { + expect(getAtmosphereAnnouncementBanner(emptyData)).toBeUndefined() + expect( + getAtmosphereAnnouncementBanner({ + ...emptyData, + announcementBanner: { + title: 'Title only', + url: 'https://example.com/announcement', + }, + }), + ).toEqual({ + id: undefined, + title: 'Title only', + description: undefined, + image: undefined, + overlayColor: undefined, + textColor: undefined, + href: 'https://example.com/announcement', + }) + expect(getAtmosphereArticles(emptyData)).toEqual([]) + expect(getAtmosphereApps(emptyData)).toEqual([]) + expect(getAtmosphereLivestreams(emptyData)).toEqual([]) + expect(getAtmospherePhotos(emptyData)).toEqual([]) + + const sparseData = parseData({ + ...emptyData, + announcementBanner: { + title: 'Title only', + url: 'https://example.com/announcement', + }, + articles: { + items: [ + { + featured: false, + view: { + uri: 'https://example.com/article', + title: 'Sparse article', + description: 'No optional card fields', + }, + }, + ], + }, + photos: { + items: [ + { + featured: false, + view: { + uri: 'https://example.com/gallery', + title: 'Sparse gallery', + description: '', + items: [ + {$type: 'app.bsky.embed.external#viewGalleryVideo'}, + image, + ], + associatedProfiles: [testProfile], + }, + }, + { + featured: false, + view: { + uri: 'https://example.com/unsupported-gallery', + title: 'No supported image', + description: '', + items: [{$type: 'app.bsky.embed.external#viewGalleryVideo'}], + associatedProfiles: [testProfile], + }, + }, + { + featured: false, + view: { + uri: 'https://example.com/gallery-without-profile', + title: 'No profile', + description: '', + items: [image], + }, + }, + ], + }, + livestreams: { + items: [ + { + featured: false, + view: { + uri: 'https://example.com/livestream-without-profile', + title: 'No profile', + description: '', + active: true, + }, + }, + ], + }, + apps: [ + {id: 'sparse-app', title: 'Sparse app', url: 'https://example.com'}, + ], + }) + + expect(getAtmosphereArticles(sparseData)[0]).toMatchObject({ + title: 'Sparse article', + image: undefined, + publisher: undefined, + publisherAvatar: undefined, + }) + expect(getAtmospherePhotos(sparseData)).toEqual([ + { + id: 'https://example.com/gallery', + href: 'https://example.com/gallery', + title: 'Sparse gallery', + image: image.thumbnail, + imageAlt: undefined, + likeCount: 0, + authorProfile: testProfile, + }, + ]) + expect(getAtmosphereLivestreams(sparseData)).toEqual([]) + expect(getAtmosphereApps(sparseData)).toEqual([ + { + id: 'sparse-app', + title: 'Sparse app', + description: undefined, + logo: undefined, + backgroundImage: undefined, + overlayColor: undefined, + textColor: undefined, + href: 'https://example.com', + }, + ]) + }) + + it('keeps associated profiles that omit $type and drops invalid ones', () => { + const {$type: _, ...implicitProfile} = testProfile + const data = parseData({ + ...emptyData, + articles: { + items: [ + { + featured: true, + view: { + uri: 'https://example.com/article', + title: 'Article', + description: '', + }, + }, + ], + }, + photos: { + items: [ + { + featured: true, + view: { + uri: 'https://example.com/gallery', + title: 'Gallery', + description: '', + items: [image], + associatedProfiles: [implicitProfile], + }, + }, + ], + }, + livestreams: { + items: [ + { + featured: true, + view: { + uri: 'https://example.com/livestream', + title: 'Livestream', + description: '', + active: true, + associatedProfiles: [implicitProfile], + }, + }, + ], + }, + }) + + expect(getAtmospherePhotos(data)).toHaveLength(1) + expect(getAtmosphereLivestreams(data)).toHaveLength(1) + + const invalidProfile = { + ...data.photos.items[0].view, + associatedProfiles: [{did: 'nope'}], + } + expect( + getAtmospherePhotos({ + ...data, + photos: {items: [{featured: true, view: invalidProfile as never}]}, + }), + ).toEqual([]) + expect(getAtmosphereLivestreams({livestreams: {items: []}})).toEqual([]) + }) + + it('validates the live response contract', () => { + expect(() => + parseData({...emptyData, apps: [{url: 'not a uri'}]}), + ).toThrow() + expect(() => + parseData({...emptyData, articles: {items: [{view: {}}]}}), + ).toThrow() + }) +}) diff --git a/src/screens/Atmosphere/data/__tests__/useAtmosphereExploreQuery.test.tsx b/src/screens/Atmosphere/data/__tests__/useAtmosphereExploreQuery.test.tsx new file mode 100644 index 000000000..c53a13809 --- /dev/null +++ b/src/screens/Atmosphere/data/__tests__/useAtmosphereExploreQuery.test.tsx @@ -0,0 +1,221 @@ +import {type PropsWithChildren} from 'react' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {renderHook, waitFor} from '@testing-library/react-native' + +import {useLanguagePrefs} from '#/state/preferences/languages' +import {useAppviewClient} from '#/state/session' +import {useAtmosphereExploreQuery} from '#/screens/Atmosphere/data/useAtmosphereExploreQuery' +import {app} from '#/lexicons' + +jest.mock('#/state/preferences/languages', () => ({ + useLanguagePrefs: jest.fn(), +})) + +jest.mock('#/state/session', () => ({ + useAppviewClient: jest.fn(), +})) + +const data: app.bsky.unspecced.getAtmosphereExploreTab.$OutputBody = { + articles: {items: []}, + publications: {items: []}, + photos: {items: []}, + livestreams: {items: []}, + apps: [], +} + +function setLanguages(contentLanguages: string[]) { + jest + .mocked(useLanguagePrefs) + .mockReturnValue({contentLanguages} as ReturnType) +} + +function setup(did: string | undefined = 'did:plc:viewer') { + const queryClient = new QueryClient({ + defaultOptions: {queries: {gcTime: Infinity, retry: false}}, + }) + const client = {did, call: jest.fn()} + jest.mocked(useAppviewClient).mockReturnValue(client as never) + setLanguages(['en']) + + const wrapper = ({children}: PropsWithChildren) => ( + {children} + ) + + return {client, queryClient, wrapper} +} + +beforeEach(() => { + jest.clearAllMocks() +}) + +describe('useAtmosphereExploreQuery', () => { + it('calls the appview client with the generated query, langs, and a signal', async () => { + const {client, wrapper} = setup() + client.call.mockResolvedValue(data) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(result.current.data).toBe(data) + expect(client.call).toHaveBeenCalledTimes(1) + expect(client.call).toHaveBeenCalledWith( + app.bsky.unspecced.getAtmosphereExploreTab, + {langs: ['en']}, + { + signal: expect.any(AbortSignal), + headers: {'Accept-Language': 'en'}, + }, + ) + }) + + it.each([ + {languages: ['en', 'fr'], header: 'en,fr'}, + {languages: ['pt-BR'], header: 'pt-BR'}, + {languages: [], header: ''}, + ])( + 'sends content languages $languages as langs and Accept-Language "$header"', + async ({languages, header}) => { + const {client, wrapper} = setup() + setLanguages(languages) + client.call.mockResolvedValue(data) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(client.call).toHaveBeenCalledWith( + app.bsky.unspecced.getAtmosphereExploreTab, + languages.length ? {langs: languages} : {}, + { + signal: expect.any(AbortSignal), + headers: {'Accept-Language': header}, + }, + ) + }, + ) + + it('refetches with a language-specific key when preferences change', async () => { + const {client, queryClient, wrapper} = setup() + client.call.mockResolvedValue(data) + + const {result, rerender} = renderHook(() => useAtmosphereExploreQuery(), { + wrapper, + }) + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + setLanguages(['fr', 'en']) + rerender({}) + + await waitFor(() => expect(client.call).toHaveBeenCalledTimes(2)) + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(client.call).toHaveBeenLastCalledWith( + app.bsky.unspecced.getAtmosphereExploreTab, + {langs: ['fr', 'en']}, + { + signal: expect.any(AbortSignal), + headers: {'Accept-Language': 'fr,en'}, + }, + ) + expect(queryClient.getQueryCache().getAll()).toHaveLength(2) + }) + + it('retains every list recommendation ID in the response and cache', async () => { + const {client, queryClient, wrapper} = setup() + const response = { + ...data, + articles: {items: [], recIdStr: '18446744073709551615'}, + publications: {items: [], recIdStr: '18446744073709551614'}, + photos: {items: [], recIdStr: '18446744073709551613'}, + livestreams: {items: [], recIdStr: '18446744073709551612'}, + } + client.call.mockResolvedValue(response) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + expect(result.current.data).toBe(response) + expect(queryClient.getQueryCache().getAll()[0].state.data).toBe(response) + expect(result.current.data?.articles.recIdStr).toBe('18446744073709551615') + }) + + it('reuses cached data before the stale time elapses', async () => { + const {client, queryClient, wrapper} = setup() + client.call.mockResolvedValue(data) + + const first = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(first.result.current.isSuccess).toBe(true)) + first.unmount() + + const second = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + expect(second.result.current.data).toBe(data) + expect(client.call).toHaveBeenCalledTimes(1) + expect(queryClient.getQueryCache().getAll()).toHaveLength(1) + }) + + it.each(['did:plc:two', undefined])( + 'isolates the cache for viewer %s', + async did => { + const {client, queryClient, wrapper} = setup('did:plc:one') + client.call.mockResolvedValue(data) + + const first = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(first.result.current.isSuccess).toBe(true)) + first.unmount() + + jest + .mocked(useAppviewClient) + .mockReturnValue({did, call: client.call} as never) + const second = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(second.result.current.isSuccess).toBe(true)) + + expect(client.call).toHaveBeenCalledTimes(2) + expect(queryClient.getQueryCache().getAll()).toHaveLength(2) + }, + ) + + it('retries once before surfacing a failure', async () => { + const {client, wrapper} = setup() + client.call.mockRejectedValue(new Error('offline')) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(result.current.isError).toBe(true), { + timeout: 3000, + }) + + expect(client.call).toHaveBeenCalledTimes(2) + }) + + it('recovers when the retry succeeds', async () => { + const {client, wrapper} = setup() + client.call + .mockRejectedValueOnce(new Error('502')) + .mockResolvedValueOnce(data) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(result.current.isSuccess).toBe(true), { + timeout: 3000, + }) + + expect(result.current.data).toBe(data) + expect(result.current.isError).toBe(false) + expect(client.call).toHaveBeenCalledTimes(2) + }) + + it('surfaces failures and recovers on refetch', async () => { + const {client, wrapper} = setup() + client.call.mockRejectedValue(new Error('offline')) + + const {result} = renderHook(() => useAtmosphereExploreQuery(), {wrapper}) + await waitFor(() => expect(result.current.isError).toBe(true), { + timeout: 3000, + }) + expect(result.current.data).toBeUndefined() + expect(client.call).toHaveBeenCalledTimes(2) + + client.call.mockResolvedValue(data) + await result.current.refetch() + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(result.current.data).toBe(data) + expect(client.call).toHaveBeenCalledTimes(3) + }) +}) diff --git a/src/screens/Atmosphere/data/exploreData.ts b/src/screens/Atmosphere/data/exploreData.ts new file mode 100644 index 000000000..5fc0f1c1d --- /dev/null +++ b/src/screens/Atmosphere/data/exploreData.ts @@ -0,0 +1,256 @@ +import {type $Typed, type l} from '@atproto/lex' + +import {hexToRgb} from '#/alf/util/colorGeneration' +import {app} from '#/lexicons' +import * as bsky from '#/types/bsky' + +export type AtmosphereData = + app.bsky.unspecced.getAtmosphereExploreTab.$OutputBody + +type AtmosphereProfileView = l.InferOutput< + typeof app.bsky.actor.defs.profileViewBasic +> +type AtmosphereViewGalleryImage = + $Typed + +export type AtmosphereArticleCardData = { + id: string + href: string + title: string + description?: string + image?: string + publisher?: string + publisherAvatar?: string +} + +export type AtmospherePublicationCardData = { + id: string + title: string + view: app.bsky.embed.external.ViewExternal +} + +export type AtmosphereAppCardData = { + id: string + title: string + description?: string + logo?: string + backgroundImage?: string + overlayColor?: string + textColor?: string + href: string +} + +export type AtmosphereAnnouncementBannerData = { + id?: string + title: string + description?: string + image?: string + overlayColor?: string + textColor?: string + href: string +} + +export type AtmospherePhotoCardData = { + id: string + href: string + title: string + image: string + imageAlt?: string + likeCount: number + authorProfile: app.bsky.actor.defs.ProfileViewBasic +} + +export type AtmosphereLivestreamCardData = { + id: string + href: string + title: string + active: boolean + activeCount?: number + image?: string + authorProfile: app.bsky.actor.defs.ProfileViewBasic +} + +/** Keeps the first item for each id, preserving order. */ +function dedupeById(items: T[]): T[] { + const seen = new Set() + return items.filter(item => { + if (seen.has(item.id)) return false + seen.add(item.id) + return true + }) +} + +function getProfile( + profiles?: AtmosphereProfileView[], +): app.bsky.actor.defs.ProfileViewBasic | undefined { + const profile = profiles?.[0] + /* + * Associated profiles from the appview omit `$type`, so a `$type` check + * would reject valid profiles. Fully validate instead, which permits an + * implicit `$type`. + */ + return bsky.matches(app.bsky.actor.defs.profileViewBasic, profile) + ? profile + : undefined +} + +function isGalleryImage(item: unknown): item is AtmosphereViewGalleryImage { + return ( + bsky.isType(app.bsky.embed.external.viewGalleryImage, item) && + bsky.matches(app.bsky.embed.external.viewGalleryImage, item) + ) +} + +export function getAtmosphereArticles( + data: AtmosphereData, +): AtmosphereArticleCardData[] { + return dedupeById( + data.articles.items.map(({view: article}) => ({ + id: article.uri, + href: article.uri, + title: article.title.trim(), + description: article.description || undefined, + image: article.image, + publisher: article.publisher?.title, + publisherAvatar: article.publisher?.logo, + })), + ).sort( + (a, b) => + Number(Boolean(b.image)) - Number(Boolean(a.image)) || + (b.description?.trim().length ?? 0) - (a.description?.trim().length ?? 0), + ) +} + +function toColorRgb( + hex?: string, +): app.bsky.embed.external.ColorRgb | undefined { + const rgb = hex ? hexToRgb(hex) : null + return rgb ?? undefined +} + +/** + * The shared publication card renders the legacy external view, so adapt the + * publication view to it instead of reimplementing the card. + */ +export function getAtmospherePublications( + data: AtmosphereData, +): AtmospherePublicationCardData[] { + return dedupeById( + data.publications.items.map(({view: publication}) => ({ + id: publication.uri, + title: publication.title, + view: { + uri: publication.uri, + title: publication.title, + description: publication.description, + thumb: publication.image, + createdAt: publication.createdAt, + updatedAt: publication.updatedAt, + labels: publication.labels, + associatedRefs: publication.associatedRefs, + associatedProfiles: publication.associatedProfiles, + source: { + uri: publication.uri, + title: publication.title, + description: publication.description, + icon: publication.logo, + theme: publication.theme && { + backgroundRGB: toColorRgb(publication.theme.background), + foregroundRGB: toColorRgb(publication.theme.foreground), + accentRGB: toColorRgb(publication.theme.accent), + accentForegroundRGB: toColorRgb(publication.theme.accentForeground), + }, + }, + }, + })), + ).sort( + (a, b) => + b.view.description.trim().length - a.view.description.trim().length, + ) +} + +export function getAtmosphereApps( + data: AtmosphereData, +): AtmosphereAppCardData[] { + return dedupeById( + data.apps.flatMap(app => { + if (!app.id || !app.title || !app.url) return [] + + return [ + { + id: app.id, + title: app.title, + description: app.description || undefined, + logo: app.logo, + backgroundImage: app.backgroundImage, + overlayColor: app.overlayColor, + textColor: app.textColor, + href: app.url, + }, + ] + }), + ) +} + +export function getAtmosphereAnnouncementBanner( + data: AtmosphereData, +): AtmosphereAnnouncementBannerData | undefined { + const banner = data.announcementBanner + if (!banner?.title || !banner.url) return undefined + + return { + id: banner.id, + title: banner.title, + description: banner.description || undefined, + image: banner.image, + overlayColor: banner.overlayColor, + textColor: banner.textColor, + href: banner.url, + } +} + +export function getAtmosphereLivestreams( + data: Pick, +): AtmosphereLivestreamCardData[] { + return dedupeById( + data.livestreams.items.flatMap(({view: livestream}) => { + const authorProfile = getProfile(livestream.associatedProfiles) + if (!authorProfile) return [] + + return [ + { + id: livestream.uri, + href: livestream.uri, + title: livestream.title.trim(), + active: livestream.active, + image: livestream.image, + authorProfile, + }, + ] + }), + ) +} + +export function getAtmospherePhotos( + data: AtmosphereData, +): AtmospherePhotoCardData[] { + return dedupeById( + data.photos.items.flatMap(({view: photo}) => { + const image = photo.items.find(isGalleryImage) + const authorProfile = getProfile(photo.associatedProfiles) + if (!image || !authorProfile) return [] + + return [ + { + id: photo.uri, + href: photo.uri, + title: photo.title, + image: image.thumbnail, + imageAlt: image.alt || undefined, + likeCount: photo.likeCount ?? 0, + authorProfile, + }, + ] + }), + ) +} diff --git a/src/screens/Atmosphere/data/useAtmosphereExploreQuery.ts b/src/screens/Atmosphere/data/useAtmosphereExploreQuery.ts new file mode 100644 index 000000000..36099f347 --- /dev/null +++ b/src/screens/Atmosphere/data/useAtmosphereExploreQuery.ts @@ -0,0 +1,30 @@ +import {useQuery} from '@tanstack/react-query' + +import {useLanguagePrefs} from '#/state/preferences/languages' +import {STALE} from '#/state/queries' +import {createQueryKey} from '#/state/queries/util' +import {useAppviewClient} from '#/state/session' +import {app} from '#/lexicons' + +export const useAtmosphereExploreQueryRoot = 'useAtmosphereExploreQuery' + +export function useAtmosphereExploreQuery() { + const client = useAppviewClient() + const {contentLanguages} = useLanguagePrefs() + const acceptLanguage = contentLanguages.join(',') + + return useQuery({ + queryKey: createQueryKey(useAtmosphereExploreQueryRoot, { + did: client.did, + acceptLanguage, + }), + staleTime: STALE.MINUTES.FIVE, + retry: 1, + queryFn: ({signal}) => + client.call( + app.bsky.unspecced.getAtmosphereExploreTab, + contentLanguages.length ? {langs: contentLanguages} : {}, + {signal, headers: {'Accept-Language': acceptLanguage}}, + ), + }) +} diff --git a/src/screens/Atmosphere.tsx b/src/screens/Atmosphere/index.tsx similarity index 66% rename from src/screens/Atmosphere.tsx rename to src/screens/Atmosphere/index.tsx index 5da0d5756..973becd5b 100644 --- a/src/screens/Atmosphere.tsx +++ b/src/screens/Atmosphere/index.tsx @@ -4,17 +4,17 @@ import {Trans, useLingui} from '@lingui/react/macro' import {Pager} from '#/view/com/pager/Pager' import {TabBar} from '#/view/com/pager/TabBar' import {NotFoundScreen} from '#/view/screens/NotFound' -import {atoms as a, useTheme, web} from '#/alf' +import {atoms as a, web} from '#/alf' import {BetaTag} from '#/components/BetaTag' -import {Earth_Stroke2_Corner0_Rounded as EarthIcon} from '#/components/icons/Earth' import * as Layout from '#/components/Layout' -import {Text} from '#/components/Typography' import {useAnalytics} from '#/analytics' +import {AtmosphereActivityTab} from './ActivityTab' +import {AtmosphereExploreTab} from './ExploreTab' export function AtmosphereScreen() { const {t: l} = useLingui() const ax = useAnalytics() - const isEnabled = ax.features.enabled(ax.features.AtmosphereExploreEnable) + const isEnabled = ax.features.enabled(ax.features.AtmosphereScreenEnable) if (!isEnabled) { return @@ -43,24 +43,9 @@ export function AtmosphereScreen() { )}> - - + + ) } - -function AtmosphereWelcome() { - const t = useTheme() - - return ( - - - - - Welcome! - - - - ) -} diff --git a/src/state/queries/nuxs/definitions.ts b/src/state/queries/nuxs/definitions.ts index ad352e225..d6a9dfbbc 100644 --- a/src/state/queries/nuxs/definitions.ts +++ b/src/state/queries/nuxs/definitions.ts @@ -7,6 +7,7 @@ export enum Nux { ExploreInterestsCard = 'ExploreInterestsCard', InitialVerificationAnnouncement = 'InitialVerificationAnnouncement', ActivitySubscriptions = 'ActivitySubscriptions', + AtmosphereNux = 'AtmosphereNux', AgeAssuranceDismissibleNotice = 'AgeAssuranceDismissibleNotice', AgeAssuranceDismissibleFeedBanner = 'AgeAssuranceDismissibleFeedBanner', BookmarksAnnouncement = 'BookmarksAnnouncement', @@ -43,6 +44,10 @@ export type AppNux = BaseNux< id: Nux.ActivitySubscriptions data: undefined } + | { + id: Nux.AtmosphereNux + data: undefined + } | { id: Nux.AgeAssuranceDismissibleNotice data: undefined @@ -94,6 +99,7 @@ export const NuxSchemas: Record | undefined> = { [Nux.ExploreInterestsCard]: undefined, [Nux.InitialVerificationAnnouncement]: undefined, [Nux.ActivitySubscriptions]: undefined, + [Nux.AtmosphereNux]: undefined, [Nux.AgeAssuranceDismissibleNotice]: undefined, [Nux.AgeAssuranceDismissibleFeedBanner]: undefined, [Nux.PolicyUpdate202508]: undefined, diff --git a/src/view/shell/Drawer.tsx b/src/view/shell/Drawer.tsx index 8853f3d57..b48dd4a50 100644 --- a/src/view/shell/Drawer.tsx +++ b/src/view/shell/Drawer.tsx @@ -213,7 +213,7 @@ let DrawerContent = ({}: React.PropsWithoutRef<{}>): React.ReactNode => { const {hasSession, currentAccount} = useSession() const inviteFriendsControl = useDialogControl() const isAtmosphereExploreEnabled = ax.features.enabled( - ax.features.AtmosphereExploreEnable, + ax.features.AtmosphereScreenEnable, ) // events diff --git a/src/view/shell/desktop/LeftNav.tsx b/src/view/shell/desktop/LeftNav.tsx index dd347f754..0edb4c84c 100644 --- a/src/view/shell/desktop/LeftNav.tsx +++ b/src/view/shell/desktop/LeftNav.tsx @@ -684,7 +684,7 @@ export function DesktopLeftNav({ const numUnreadMessages = useUnreadMessageCount() const hasHomeBadge = useHomeBadge() const isAtmosphereExploreEnabled = ax.features.enabled( - ax.features.AtmosphereExploreEnable, + ax.features.AtmosphereScreenEnable, ) const insets = useSafeAreaInsets() -- knotmirror 0.0.1