diff --git a/bskyogcard/src/components/Event.tsx b/bskyogcard/src/components/Event.tsx new file mode 100644 index 000000000..8c8298a2e --- /dev/null +++ b/bskyogcard/src/components/Event.tsx @@ -0,0 +1,293 @@ +/* eslint-disable bsky-internal/avoid-unwrapped-text */ +import {Cluster} from './Cluster.js' +import {Img} from './Img.js' + +export const EVENT_HEIGHT = 630 +export const EVENT_WIDTH = 1200 + +export type EventCardData = { + name: string + longDate?: string + timeRange?: string + place?: string + cancelled: boolean + host: string + posterColors: string[] + posterEmoji: string +} + +type Rec = Record + +const asRec = (v: unknown): Rec | undefined => + v && typeof v === 'object' && !Array.isArray(v) ? (v as Rec) : undefined +const asStr = (v: unknown): string | undefined => + typeof v === 'string' && v.length > 0 ? v : undefined +const asDate = (v: unknown): Date | undefined => { + const s = asStr(v) + const d = s ? new Date(s) : undefined + return d && !isNaN(d.getTime()) ? d : undefined +} +const validZone = (zone: string | undefined) => { + if (!zone) return + try { + new Intl.DateTimeFormat('en-US', {timeZone: zone}) + return zone + } catch { + return + } +} + +function describePlace(record: Rec): string | undefined { + const locations = Array.isArray(record.locations) ? record.locations : [] + for (const item of locations) { + const loc = asRec(item) + if (!loc || asStr(loc.uri)) continue + const parts = [asStr(loc.name), asStr(loc.street), asStr(loc.locality)] + const text = parts.filter(Boolean).join(', ') + if (text) return text + } + const mode = asStr(record.mode) + if (mode?.endsWith('#virtual') || mode?.endsWith('#hybrid')) return 'Online' +} + +// Mirrors src/features/events/poster.ts in the app so the card matches. +const POSTER_GRADIENTS = [ + ['#464985', '#6060E9', '#8686FF'], + ['#0A7AFF', '#59B9FF'], + ['#022C5E', '#4079BC'], + ['#4E90AE', '#AEA3AB', '#E6A98F', '#F3A84C'], + ['#6772AF', '#B88BB6', '#FFA6AC'], + ['#FF6A56', '#FF9156', '#FFDD87'], + ['#083367', '#9EE8C1'], + ['#203E4E', '#755B62', '#CD7765', '#EF956E'], +] + +const POSTER_KEYWORDS: [RegExp, string][] = [ + [/\b(open mic|karaoke|poetry slam|spoken word)\b/i, '๐ŸŽค'], + [/\b(party|parties|birthday|celebration|launch|mixer)\b/i, '๐ŸŽ‰'], + [/\b(music|dj|concert|gig|band|jam|listening|album)\b/i, '๐ŸŽถ'], + [/\b(film|films|movie|movies|screening|cinema)\b/i, '๐ŸŽฌ'], + [/\b(book|books|reading|library|writing)\b/i, '๐Ÿ“š'], + [ + /\b(brunch|breakfast|lunch|dinner|potluck|cookout|bbq|barbecue|picnic|food)\b/i, + '๐Ÿฝ๏ธ', + ], + [/\b(coffee|tea)\b/i, 'โ˜•'], + [/\b(run|running|walk|hike|yoga|workout|fitness|bike|ride)\b/i, '๐Ÿƒ'], + [/\b(game|games|gaming|trivia|tournament)\b/i, '๐ŸŽฎ'], + [/\b(art|gallery|exhibit|exhibition|museum|craft|crafts)\b/i, '๐ŸŽจ'], + [/\b(dance|dancing)\b/i, '๐Ÿ’ƒ'], + [/\b(workshop|class|talk|lecture|panel|conference|study)\b/i, '๐ŸŽ“'], + [ + /\b(meeting|meetup|wg|working group|standup|sync|office hours|town hall|call)\b/i, + '๐Ÿ’ฌ', + ], + [/\b(protest|rally|march|vigil)\b/i, 'โœŠ'], +] + +function hash(str: string) { + let h = 0x811c9dc5 + for (let i = 0; i < str.length; i++) { + h ^= str.charCodeAt(i) + h = Math.imul(h, 0x01000193) + } + return h >>> 0 +} + +function posterEmoji(rec: Rec, name: string) { + for (const text of [name, asStr(rec.description)]) { + if (!text) continue + const match = POSTER_KEYWORDS.find(([re]) => re.test(text)) + if (match) return match[1] + } + const links = [ + ...(Array.isArray(rec.uris) ? rec.uris : []), + ...(Array.isArray(rec.locations) ? rec.locations : []), + ] + const streamplace = links.some(item => { + const uri = asStr(asRec(item)?.uri) + try { + return !!uri && /^(www\.)?stream\.place$/.test(new URL(uri).hostname) + } catch { + return false + } + }) + const mode = asStr(rec.mode) + if (streamplace) return '๐Ÿ“บ' + if (mode?.endsWith('#virtual')) return '๐Ÿ’ป' + if (mode?.endsWith('#hybrid')) return '๐ŸŒ' + if (mode?.endsWith('#inperson')) return '๐Ÿ“' + return '๐Ÿ“…' +} + +export function toEventCardData(record: unknown, host: string, uri: string) { + const rec = asRec(record) + const name = asStr(rec?.name) + if (!rec || !name) return + const startsAt = asDate(rec.startsAt) + const endsAt = asDate(rec.endsAt) + const timeZone = validZone(asStr(rec.timezone)) ?? 'UTC' + const fmt = (options: Intl.DateTimeFormatOptions, date: Date) => + new Intl.DateTimeFormat('en-US', {...options, timeZone}).format(date) + const time = {hour: 'numeric', minute: '2-digit'} as const + let longDate: string | undefined + let timeRange: string | undefined + if (startsAt) { + longDate = fmt({weekday: 'long', month: 'long', day: 'numeric'}, startsAt) + const zone = fmt({timeZoneName: 'short'}, startsAt).split(' ').pop() + const start = fmt(time, startsAt) + timeRange = + `${endsAt ? `${start} โ€“ ${fmt(time, endsAt)}` : start} ${zone ?? ''}`.trim() + } + return { + name, + longDate, + timeRange, + place: describePlace(rec), + cancelled: asStr(rec.status)?.endsWith('#cancelled') ?? false, + host, + posterColors: POSTER_GRADIENTS[hash(uri) % POSTER_GRADIENTS.length], + posterEmoji: posterEmoji(rec, name), + } satisfies EventCardData +} + +export function EventCard({ + event, + cover, +}: { + event: EventCardData + cover: Buffer | null +}) { + return ( +
+ {cover ? ( + + ) : ( +
+ {event.posterEmoji} +
+ )} +
+ {event.cancelled && ( +
+ Cancelled +
+ )} + {event.longDate && ( +
+ {event.longDate} +
+ )} +
+ {event.name} +
+ {event.timeRange && ( +
+ {event.timeRange} +
+ )} + {event.place && ( +
+ {'๐Ÿ“ ' + event.place} +
+ )} +
+
+ +
+ {'Hosted by ' + event.host} +
+
+
+
+ ) +} diff --git a/bskyogcard/src/routes/event.tsx b/bskyogcard/src/routes/event.tsx new file mode 100644 index 000000000..1afeabd48 --- /dev/null +++ b/bskyogcard/src/routes/event.tsx @@ -0,0 +1,91 @@ +import resvg from '@resvg/resvg-js' +import {type Express} from 'express' +import satori from 'satori' + +import { + EVENT_HEIGHT, + EVENT_WIDTH, + EventCard, + toEventCardData, +} from '../components/Event.js' +import {type AppContext} from '../context.js' +import {httpLogger} from '../logger.js' +import {loadEmojiAsSvg} from '../util.js' +import {getImage, handler, originVerifyMiddleware} from './util.js' + +type EventView = { + record: unknown + thumb?: string + creator: {did: string; handle: string; displayName?: string} +} + +const DID_RE = /^did:[a-z]+:[a-zA-Z0-9._:%-]+$/ +const RKEY_RE = /^[a-zA-Z0-9._:~-]{1,512}$/ + +// satori can't decode WebP, and a failed decode would fail the whole card. +const isJpegOrPng = (buf: Buffer) => + (buf[0] === 0xff && buf[1] === 0xd8) || (buf[0] === 0x89 && buf[1] === 0x50) + +export default function (ctx: AppContext, app: Express) { + return app.get( + '/event/:did/:rkey', + originVerifyMiddleware(ctx), + handler(async (req, res) => { + const {did, rkey} = req.params + if (!DID_RE.test(did) || !RKEY_RE.test(rkey)) { + return res.status(404).end('not found') + } + const uri = `at://${did}/community.lexicon.calendar.event/${rkey}` + let event: EventView | undefined + try { + const url = new URL( + '/xrpc/community.blacksky.calendar.getEvents', + ctx.cfg.service.appviewUrl, + ) + url.searchParams.set('uris', uri) + const response = await fetch(url) + if (response.ok) { + const body = (await response.json()) as {events?: EventView[]} + event = body.events?.[0] + } + } catch (err) { + httpLogger.warn({err, uri}, 'could not fetch event') + } + const data = + event && + toEventCardData( + event.record, + event.creator.displayName || `@${event.creator.handle}`, + uri, + ) + if (!event || !data) return res.status(404).end('not found') + + let cover: Buffer | null = null + if (event.thumb) { + try { + cover = await getImage(event.thumb) + if (cover && !isJpegOrPng(cover)) cover = null + } catch (err) { + httpLogger.warn({err, uri}, 'could not fetch event cover') + } + } + + const svg = await satori(, { + fonts: ctx.fonts, + height: EVENT_HEIGHT, + width: EVENT_WIDTH, + loadAdditionalAsset: async (lang, text) => { + if (lang === 'emoji') { + return (await loadEmojiAsSvg(text)) ?? '' + } + return '' + }, + }) + const output = await resvg.renderAsync(svg) + res.statusCode = 200 + res.setHeader('content-type', 'image/png') + res.setHeader('cdn-tag', did) + return res.end(output.asPng()) + }), + ) +} diff --git a/bskyogcard/src/routes/index.ts b/bskyogcard/src/routes/index.ts index 5c2a26e98..ad44a55fb 100644 --- a/bskyogcard/src/routes/index.ts +++ b/bskyogcard/src/routes/index.ts @@ -3,6 +3,7 @@ import {type Express} from 'express' import {type AppContext} from '../context.js' import {default as avatarBubbles} from './avatar-bubbles.js' import {default as chatInvite} from './chat-invite.js' +import {default as event} from './event.js' import {default as health} from './health.js' import {default as starterPack} from './starter-pack.js' @@ -12,6 +13,7 @@ export default function (ctx: AppContext, app: Express) { app = health(ctx, app) // GET /_health app = starterPack(ctx, app) // GET /start/:actor/:rkey app = chatInvite(ctx, app) // GET /chat-invite/:code + app = event(ctx, app) // GET /event/:did/:rkey app = avatarBubbles(ctx, app) // GET /avatar-bubbles?dids=... return app } diff --git a/bskyweb/cmd/bskyweb/event.go b/bskyweb/cmd/bskyweb/event.go new file mode 100644 index 000000000..462032c2f --- /dev/null +++ b/bskyweb/cmd/bskyweb/event.go @@ -0,0 +1,100 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + appbsky "github.com/bluesky-social/indigo/api/bsky" + "github.com/bluesky-social/indigo/atproto/syntax" + "github.com/bluesky-social/indigo/xrpc" + "github.com/labstack/echo/v4" +) + +type eventPreview struct { + Name string + Description string + Thumb string +} + +type eventRecordFields struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type getEventsOutput struct { + Events []struct { + Thumb string `json:"thumb"` + Record json.RawMessage `json:"record"` + } `json:"events"` +} + +func (srv *Server) fetchEventPreview(ctx context.Context, did, rkey string) (*eventPreview, error) { + uri := fmt.Sprintf("at://%s/community.lexicon.calendar.event/%s", did, rkey) + var out getEventsOutput + params := map[string]any{"uris": uri} + if err := srv.xrpcc.Do(ctx, xrpc.Query, "", "community.blacksky.calendar.getEvents", params, nil, &out); err != nil { + return nil, err + } + return eventPreviewFromOutput(&out), nil +} + +func eventPreviewFromOutput(out *getEventsOutput) *eventPreview { + if len(out.Events) == 0 { + return nil + } + var rec eventRecordFields + if err := json.Unmarshal(out.Events[0].Record, &rec); err != nil || rec.Name == "" { + return nil + } + return &eventPreview{ + Name: rec.Name, + Description: rec.Description, + Thumb: out.Events[0].Thumb, + } +} + +func (srv *Server) WebEvent(c echo.Context) error { + req := c.Request() + ctx := req.Context() + data := srv.NewTemplateContext(req) + data["requestURI"] = fmt.Sprintf("https://%s%s", req.Host, req.URL.Path) + + rkey, err := syntax.ParseRecordKey(c.Param("rkey")) + if err != nil { + return c.Render(http.StatusOK, "event.html", data) + } + handleOrDID, err := syntax.ParseAtIdentifier(c.Param("handleOrDID")) + if err != nil { + return c.Render(http.StatusOK, "event.html", data) + } + + pv, err := appbsky.ActorGetProfile(ctx, srv.xrpcc, handleOrDID.Normalize().String()) + if err != nil { + log.Warnf("failed to fetch profile for event host: %s\t%v", handleOrDID, err) + return c.Render(http.StatusOK, "event.html", data) + } + if profileRequiresAuth(pv) { + data["noindex"] = true + data["nofollow"] = true + return c.Render(http.StatusOK, "event.html", data) + } + + ev, err := srv.fetchEventPreview(ctx, pv.Did, rkey.String()) + if err != nil { + log.Warnf("failed to fetch event: %s/%s\t%v", pv.Did, rkey, err) + } + if ev == nil { + return c.Render(http.StatusOK, "event.html", data) + } + + data["title"] = ev.Name + data["description"] = ev.Description + if srv.cfg.ogcardHost != "" { + data["imgThumbUrl"] = fmt.Sprintf("%s/event/%s/%s", srv.cfg.ogcardHost, pv.Did, rkey) + } else if ev.Thumb != "" { + data["imgThumbUrl"] = ev.Thumb + } + return c.Render(http.StatusOK, "event.html", data) +} diff --git a/bskyweb/cmd/bskyweb/event_test.go b/bskyweb/cmd/bskyweb/event_test.go new file mode 100644 index 000000000..1e5ac82aa --- /dev/null +++ b/bskyweb/cmd/bskyweb/event_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/flosch/pongo2/v6" +) + +func decodeEvents(t *testing.T, body string) *getEventsOutput { + t.Helper() + var out getEventsOutput + if err := json.Unmarshal([]byte(body), &out); err != nil { + t.Fatal(err) + } + return &out +} + +func TestEventPreviewFromOutput(t *testing.T) { + ev := eventPreviewFromOutput(decodeEvents(t, `{"events":[{"thumb":"https://cdn/img@jpeg","record":{"name":"Block party","description":"Bring a dish"}}]}`)) + if ev == nil || ev.Name != "Block party" || ev.Description != "Bring a dish" || ev.Thumb != "https://cdn/img@jpeg" { + t.Fatalf("unexpected preview: %+v", ev) + } +} + +func TestEventPreviewFromOutput_MissingOrNameless(t *testing.T) { + for _, body := range []string{ + `{"events":[]}`, + `{"events":[{"record":{"description":"no name"}}]}`, + `{"events":[{"record":"not an object"}]}`, + } { + if ev := eventPreviewFromOutput(decodeEvents(t, body)); ev != nil { + t.Errorf("expected nil for %s, got %+v", body, ev) + } + } +} + +func TestRenderEvent_OpenGraph(t *testing.T) { + html := renderTemplate(t, "event.html", pongo2.Context{ + "brandName": "Blacksky", + "requestURI": "https://blacksky.community/event/bob.test/3kabc", + "title": "Block party", + "description": "Bring a dish", + "imgThumbUrl": "https://ogcard.example/event/did:plc:bob/3kabc", + }) + for _, want := range []string{ + `Block party - Blacksky`, + ``, + ``, + ``, + ``, + } { + if !strings.Contains(html, want) { + t.Errorf("missing %s in:\n%s", want, html) + } + } +} + +func TestRenderEvent_NoDescriptionFallback(t *testing.T) { + html := renderTemplate(t, "event.html", pongo2.Context{"brandName": "Blacksky", "title": "Block party"}) + if !strings.Contains(html, ``) { + t.Errorf("missing fallback description:\n%s", html) + } +} diff --git a/bskyweb/cmd/bskyweb/server.go b/bskyweb/cmd/bskyweb/server.go index 65d1d8241..29330ecb9 100644 --- a/bskyweb/cmd/bskyweb/server.go +++ b/bskyweb/cmd/bskyweb/server.go @@ -420,6 +420,7 @@ func serve(cctx *cli.Context) error { // chat invites e.GET("/chat/:code", server.WebChatInvite) + e.GET("/event/:handleOrDID/:rkey", server.WebEvent) // bookmarks e.GET("/saved", server.WebGenericNoindex) diff --git a/bskyweb/templates/event.html b/bskyweb/templates/event.html new file mode 100644 index 000000000..896fbf989 --- /dev/null +++ b/bskyweb/templates/event.html @@ -0,0 +1,34 @@ +{% extends "base.html" %} + +{% block head_title %}{% if title %}{{ title }} - {{ brandName }}{% else %}{{ brandTitle }}{% endif %}{% endblock %} + +{% block html_head_extra -%} + {%- if requestURI %} + + {% endif -%} + {%- if imgThumbUrl %} + + + {%- else -%} + + + {% endif -%} + + {%- if title %} + + + + {%- else -%} + + + {% endif -%} + {%- if description %} + + + + {%- elif title %} + + + + {% endif -%} +{%- endblock %} diff --git a/src/Navigation.tsx b/src/Navigation.tsx index 7d1066128..c59d68ec7 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -81,6 +81,7 @@ import {createNativeStackNavigatorWithAuth} from '#/view/shell/createNativeStack import {BookmarksScreen} from '#/screens/Bookmarks' import {Ios26CrashRegressionScreen} from '#/screens/E2E/Ios26CrashRegressionScreen' import {SharedPreferencesTesterScreen} from '#/screens/E2E/SharedPreferencesTesterScreen' +import {EventScreen} from '#/screens/Event/EventScreen' import {FindContactsFlowScreen} from '#/screens/FindContactsFlowScreen' import HashtagScreen from '#/screens/Hashtag' import {LogScreen} from '#/screens/Log' @@ -185,6 +186,11 @@ function commonScreens(Stack: typeof Flat, unreadCountLabel?: string) { component={ListsScreen} options={{title: title(msg`Lists`), requireAuth: true}} /> + ModerationScreen} diff --git a/src/analytics/features/index.ts b/src/analytics/features/index.ts index 427755f7e..6cc4cdd55 100644 --- a/src/analytics/features/index.ts +++ b/src/analytics/features/index.ts @@ -36,6 +36,19 @@ export const features = new GrowthBook({ clientKey: env.GROWTHBOOK_CLIENT_KEY, }) +// Dev builds only: EXPO_PUBLIC_FORCE_FEATURES=a,b turns those flags on locally. +const FORCE_FEATURES: string = process.env.EXPO_PUBLIC_FORCE_FEATURES || '' +if (__DEV__ && FORCE_FEATURES) { + features.setForcedFeatures( + new Map( + FORCE_FEATURES.split(',') + .map(key => key.trim()) + .filter(Boolean) + .map(key => [key, true]), + ), + ) +} + /** * Initializer promise that must be awaited before using the GrowthBook * instance or rendering the `AnalyticsFeaturesContext`. Note: this may not be diff --git a/src/analytics/features/types.ts b/src/analytics/features/types.ts index 6bdb06d0f..51bf5e540 100644 --- a/src/analytics/features/types.ts +++ b/src/analytics/features/types.ts @@ -19,6 +19,7 @@ export enum Features { SearchAppviewRoute = 'search_appview:route', StreamplaceWatchEnable = 'streamplace:watch:enable', PollsEnable = 'polls:enable', + EventsEnable = 'events:enable', AATest = 'aa-test', } diff --git a/src/components/Post/Embed/index.tsx b/src/components/Post/Embed/index.tsx index bee7e71d5..16a9eab64 100644 --- a/src/components/Post/Embed/index.tsx +++ b/src/components/Post/Embed/index.tsx @@ -10,6 +10,7 @@ import { import {Trans} from '@lingui/react/macro' import {useQueryClient} from '@tanstack/react-query' +import {useBrand} from '#/lib/community' import {postPermalink} from '#/lib/routes/links' import {getChatInviteCodeFromUrl} from '#/lib/strings/url-helpers' import {useModerationOpts} from '#/state/preferences/moderation-opts' @@ -28,6 +29,9 @@ import {isStandardSiteEmbed} from '#/components/Post/Embed/StandardSiteEmbed/uti import {RichText} from '#/components/RichText' import {Embed as StarterPackCard} from '#/components/StarterPack/StarterPackCard' import {SubtleHover} from '#/components/SubtleHover' +import {useAnalytics} from '#/analytics' +import {EventEmbed} from '#/features/events/components/EventEmbed' +import {parseEventUrl} from '#/features/events/url' import * as bsky from '#/types/bsky' import { type Embed as TEmbed, @@ -85,6 +89,8 @@ function MediaEmbed({ }: CommonProps & { embed: TEmbed }) { + const ax = useAnalytics() + const brand = useBrand() switch (embed.type) { case 'images': case 'gallery': { @@ -110,6 +116,23 @@ function MediaEmbed({ ) } + const eventRef = ax.features.enabled(ax.features.EventsEnable) + ? parseEventUrl(embed.view.external.uri, [brand.web.domains.main]) + : undefined + if (eventRef) { + return ( + + + + ) + } const chatInviteCode = getChatInviteCodeFromUrl(embed.view.external.uri) if (chatInviteCode) { return ( diff --git a/src/features/events/__tests__/events.test.ts b/src/features/events/__tests__/events.test.ts new file mode 100644 index 000000000..b2298b4fe --- /dev/null +++ b/src/features/events/__tests__/events.test.ts @@ -0,0 +1,420 @@ +import {describe, expect, it} from '@jest/globals' + +import {eventDateParts, eventPhase, formatEventTime} from '../format' +import {eventPoster} from '../poster' +import {coverUrl, parseEventRecord} from '../record' +import {applyRsvp} from '../rsvp-state' +import {mergeEventTimeline} from '../timeline' +import { + type EventView, + RSVP_GOING, + RSVP_INTERESTED, + RSVP_NOTGOING, +} from '../types' +import {makeEventLink, parseEventUrl} from '../url' + +describe('parseEventRecord', () => { + it('reads the published fields and common extensions', () => { + const parsed = parseEventRecord({ + $type: 'community.lexicon.calendar.event', + name: 'Block party', + description: 'Bring a dish', + startsAt: '2026-10-01T23:00:00.000Z', + endsAt: '2026-10-02T02:00:00.000Z', + timezone: 'America/New_York', + mode: 'community.lexicon.calendar.event#hybrid', + status: 'community.lexicon.calendar.event#cancelled', + locations: [ + { + $type: 'community.lexicon.location.address', + name: 'Park', + street: '1 Main St', + locality: 'Brooklyn', + country: 'US', + }, + {uri: 'https://example.com/zoom', name: 'Zoom'}, + ], + uris: [{uri: 'https://stream.place/did:plc:host', name: 'Streamplace'}], + }) + expect(parsed).toMatchObject({ + name: 'Block party', + description: 'Bring a dish', + timezone: 'America/New_York', + mode: 'hybrid', + cancelled: true, + location: 'Park, 1 Main St, Brooklyn', + streamplaceUrl: 'https://stream.place/did:plc:host', + joinUrl: 'https://example.com/zoom', + }) + expect(parsed?.startsAt?.toISOString()).toBe('2026-10-01T23:00:00.000Z') + expect(parsed?.links.map(link => link.uri)).toEqual([ + 'https://stream.place/did:plc:host', + 'https://example.com/zoom', + ]) + }) + + it('drops malformed optional fields instead of the event', () => { + const parsed = parseEventRecord({ + name: 'Loose', + startsAt: 'next tuesday', + timezone: 'Mars/Olympus', + mode: 'somewhere', + locations: [null, 'text', {country: 'CA'}], + uris: [{name: 'no uri'}], + }) + expect(parsed).toEqual({ + name: 'Loose', + description: undefined, + startsAt: undefined, + endsAt: undefined, + timezone: undefined, + mode: undefined, + cancelled: false, + location: 'CA', + links: [], + streamplaceUrl: undefined, + joinUrl: undefined, + }) + }) + + it('takes the join link from uris when an online event has no uri location', () => { + const parsed = parseEventRecord({ + name: 'Atmospheric Groups WG Meeting', + mode: 'community.lexicon.calendar.event#virtual', + uris: [{uri: 'https://meet.google.com/hcp-doqs-znu', name: ''}], + }) + expect(parsed?.joinUrl).toBe('https://meet.google.com/hcp-doqs-znu') + }) + + it('prefers a uri location over uris, and has no join link in person', () => { + const uris = [{uri: 'https://example.com/agenda'}] + const locations = [{uri: 'https://zoom.us/j/1'}] + expect( + parseEventRecord({ + name: 'x', + mode: 'community.lexicon.calendar.event#hybrid', + uris, + locations, + })?.joinUrl, + ).toBe('https://zoom.us/j/1') + expect(parseEventRecord({name: 'x', uris, locations})?.joinUrl).toBe( + undefined, + ) + }) + + it('drops links that are not http or https', () => { + const parsed = parseEventRecord({ + name: 'x', + mode: 'community.lexicon.calendar.event#virtual', + locations: [{uri: 'javascript:alert(1)'}], + uris: [ + {uri: 'javascript://stream.place/%0Aalert(1)'}, + {uri: 'intent://scan/#Intent;scheme=zxing;end'}, + {uri: 'tel:+15555550100'}, + {uri: 'https://example.com/agenda', name: 'Agenda'}, + ], + }) + expect(parsed?.links).toEqual([ + {uri: 'https://example.com/agenda', name: 'Agenda'}, + ]) + expect(parsed?.streamplaceUrl).toBe(undefined) + expect(parsed?.joinUrl).toBe('https://example.com/agenda') + }) + + it('rejects records without a name', () => { + expect(parseEventRecord({startsAt: '2026-10-01T00:00:00Z'})).toBe(undefined) + expect(parseEventRecord(null)).toBe(undefined) + expect(parseEventRecord(['name'])).toBe(undefined) + }) +}) + +describe('parseEventUrl', () => { + it('recognises Blacksky, atmo.rsvp and Smoke Signal event links', () => { + expect( + parseEventUrl('https://blacksky.community/event/alice.test/3kabc'), + ).toEqual({actor: 'alice.test', rkey: '3kabc'}) + expect( + parseEventUrl('https://staging.blacksky.community/event/did:plc:x/3kabc'), + ).toEqual({actor: 'did:plc:x', rkey: '3kabc'}) + expect(parseEventUrl('https://atmo.rsvp/p/alice.test/e/3kabc')).toEqual({ + actor: 'alice.test', + rkey: '3kabc', + }) + expect(parseEventUrl('https://smokesignal.events/did:plc:x/3kabc')).toEqual( + {actor: 'did:plc:x', rkey: '3kabc'}, + ) + }) + + it('ignores other links', () => { + for (const url of [ + 'https://blacksky.community/profile/alice.test', + 'https://blacksky.community/event/alice/3kabc', + 'https://example.com/event/alice.test/3kabc', + 'https://smokesignal.events/about', + 'not a url', + 'https://example.com/sale-50%-off', + 'https://example.com/a%E0%A4%A', + 'https://blacksky.community/event/alice.test/%E0%A4%A', + ]) { + expect(parseEventUrl(url)).toBe(undefined) + } + }) + + it('recognises the active brand domain when given', () => { + const url = 'https://theinvite.community/event/alice.test/3kabc' + expect(parseEventUrl(url)).toBe(undefined) + expect(parseEventUrl(url, ['https://theinvite.community'])).toEqual({ + actor: 'alice.test', + rkey: '3kabc', + }) + }) + + it('builds links the parser reads back', () => { + expect( + makeEventLink({did: 'did:plc:x', handle: 'handle.invalid'}, 'k'), + ).toBe('/event/did:plc:x/k') + expect(makeEventLink({did: 'did:plc:x', handle: ''}, 'k')).toBe( + '/event/did:plc:x/k', + ) + const link = makeEventLink( + {did: 'did:plc:x', handle: 'alice.test'}, + '3kabc', + ) + expect(link).toBe('/event/alice.test/3kabc') + expect(parseEventUrl(`https://blacksky.community${link}`)).toEqual({ + actor: 'alice.test', + rkey: '3kabc', + }) + }) +}) + +describe('eventDateParts', () => { + const base = {name: 'x', cancelled: false, links: []} + + it('shows the end date when the event ends on a later day', () => { + const parts = eventDateParts( + { + ...base, + startsAt: new Date('2026-10-02T23:00:00.000Z'), + endsAt: new Date('2026-10-04T21:00:00.000Z'), + timezone: 'America/New_York', + }, + 'en-US', + ) + expect(parts?.timeRange).toBe('7:00 PM โ€“ Sun, Oct 4, 5:00 PM EDT') + }) + + it('shows only times when the event ends the same day', () => { + const parts = eventDateParts( + { + ...base, + startsAt: new Date('2026-10-02T23:00:00.000Z'), + endsAt: new Date('2026-10-03T02:00:00.000Z'), + timezone: 'America/New_York', + }, + 'en-US', + ) + expect(parts?.timeRange).toBe('7:00 PM โ€“ 10:00 PM EDT') + }) +}) + +describe('formatEventTime', () => { + const base = {name: 'x', cancelled: false, links: []} + + it('shows the event timezone and the local time when they differ', () => { + const time = formatEventTime( + { + ...base, + startsAt: new Date('2026-10-01T23:00:00.000Z'), + timezone: 'Asia/Tokyo', + }, + 'en-US', + ) + expect(time?.primary).toContain('Oct 2') + expect(time?.local).toBeDefined() + }) + + it('omits the local time when there is no event timezone', () => { + const time = formatEventTime( + {...base, startsAt: new Date('2026-10-01T23:00:00.000Z')}, + 'en-US', + ) + expect(time?.local).toBe(undefined) + expect(formatEventTime(base, 'en-US')).toBe(undefined) + }) +}) + +describe('applyRsvp', () => { + const event = (status?: string): EventView => ({ + uri: 'at://did:plc:host/community.lexicon.calendar.event/1', + cid: 'cid', + creator: {did: 'did:plc:host', handle: 'host.test'}, + record: {}, + goingCount: 3, + interestedCount: 2, + viewer: status ? {rsvp: {uri: 'at://me/rsvp/1', status}} : {}, + indexedAt: '', + }) + + it('moves the viewer between counts', () => { + const next = applyRsvp(event(RSVP_INTERESTED), { + uri: 'at://me/rsvp/1', + status: RSVP_GOING, + }) + expect([next.goingCount, next.interestedCount]).toEqual([4, 1]) + expect(next.viewer?.rsvp?.status).toBe(RSVP_GOING) + }) + + it('removes the viewer and never goes below zero', () => { + const removed = applyRsvp(event(RSVP_GOING), undefined) + expect([removed.goingCount, removed.viewer?.rsvp]).toEqual([2, undefined]) + const empty = applyRsvp({...event(RSVP_GOING), goingCount: 0}, undefined) + expect(empty.goingCount).toBe(0) + }) + + it('does not count not-going', () => { + const next = applyRsvp(event(), {uri: 'u', status: RSVP_NOTGOING}) + expect([next.goingCount, next.interestedCount]).toEqual([3, 2]) + }) +}) + +describe('eventPhase', () => { + const now = new Date('2026-10-01T20:00:00.000Z') + const base = {name: 'x', cancelled: false, links: []} + const at = (iso: string) => new Date(iso) + + it('is upcoming before the start', () => { + expect( + eventPhase({...base, startsAt: at('2026-10-01T21:00:00Z')}, now), + ).toBe('upcoming') + }) + + it('is current between start and end, and past after the end', () => { + const event = { + ...base, + startsAt: at('2026-10-01T18:00:00Z'), + endsAt: at('2026-10-01T22:00:00Z'), + } + expect(eventPhase(event, now)).toBe('current') + expect(eventPhase(event, at('2026-10-01T22:00:00Z'))).toBe('past') + }) + + it('assumes four hours when there is no end time', () => { + expect( + eventPhase({...base, startsAt: at('2026-10-01T16:30:00Z')}, now), + ).toBe('current') + expect( + eventPhase({...base, startsAt: at('2026-10-01T15:59:00Z')}, now), + ).toBe('past') + }) + + it('has no phase without a start time', () => { + expect(eventPhase(base, now)).toBe(undefined) + }) +}) + +describe('mergeEventTimeline', () => { + const now = new Date('2026-10-01T20:00:00.000Z') + const view = (rkey: string, startsAt: string): EventView => ({ + uri: `at://did:plc:host/community.lexicon.calendar.event/${rkey}`, + cid: 'cid', + creator: {did: 'did:plc:host', handle: 'host.test'}, + record: {name: rkey, startsAt}, + goingCount: 0, + interestedCount: 0, + indexedAt: '', + }) + + it('puts happening-now first, then upcoming, then past, without duplicates', () => { + const soon = view('soon', '2026-10-02T00:00:00Z') + const later = view('later', '2026-10-05T00:00:00Z') + const live = view('live', '2026-10-01T19:00:00Z') + const old = view('old', '2026-09-01T00:00:00Z') + const merged = mergeEventTimeline([soon, later], [live, old, soon], now) + expect(merged.map(e => (e.record as {name: string}).name)).toEqual([ + 'live', + 'soon', + 'later', + 'old', + ]) + }) +}) + +describe('coverUrl', () => { + const label = (val: string) => ({ + src: 'did:plc:labeler', + uri: 'at://did:plc:host/community.lexicon.calendar.event/k', + val, + cts: '2026-09-29T00:00:00.000Z', + }) + + it('hides the cover when the event carries a sensitive label', () => { + expect(coverUrl({thumb: 'https://cdn/x', labels: [label('porn')]})).toBe( + undefined, + ) + expect( + coverUrl({thumb: 'https://cdn/x', labels: [label('graphic-media')]}), + ).toBe(undefined) + }) + + it('keeps the cover otherwise', () => { + expect(coverUrl({thumb: 'https://cdn/x', labels: [label('spoiler')]})).toBe( + 'https://cdn/x', + ) + expect(coverUrl({thumb: 'https://cdn/x'})).toBe('https://cdn/x') + }) +}) + +describe('eventPoster', () => { + const base = {name: 'x', cancelled: false, links: []} + const uri = 'at://did:plc:host/community.lexicon.calendar.event/3kabc' + + it('picks the same gradient for the same event, and varies across events', () => { + const first = eventPoster(uri, base).gradient + expect(eventPoster(uri, base).gradient).toBe(first) + const seen = new Set( + Array.from( + {length: 40}, + (_, i) => eventPoster(`${uri}${i}`, base).gradient, + ), + ) + expect(seen.size).toBeGreaterThan(3) + }) + + it.each([ + ['Block party on Nostrand', '๐ŸŽ‰'], + ['Listening session (live)', '๐ŸŽถ'], + ['Rooftop screening', '๐ŸŽฌ'], + ['Atmospheric Groups WG Meeting', '๐Ÿ’ฌ'], + ["Alice's book club", '๐Ÿ“š'], + ['Summer cookout', '๐Ÿฝ๏ธ'], + ['Open mic night', '๐ŸŽค'], + ])('matches keywords in the name: %s', (name, emoji) => { + expect(eventPoster(uri, {...base, name}).emoji).toBe(emoji) + }) + + it('falls back to the description, then the attendance mode', () => { + expect( + eventPoster(uri, {...base, name: 'Saturday', description: 'Bring a book'}) + .emoji, + ).toBe('๐Ÿ“š') + expect(eventPoster(uri, {...base, mode: 'virtual'}).emoji).toBe('๐Ÿ’ป') + expect(eventPoster(uri, {...base, mode: 'hybrid'}).emoji).toBe('๐ŸŒ') + expect(eventPoster(uri, {...base, mode: 'inperson'}).emoji).toBe('๐Ÿ“') + expect( + eventPoster(uri, { + ...base, + mode: 'virtual', + streamplaceUrl: 'https://stream.place/did:plc:x', + }).emoji, + ).toBe('๐Ÿ“บ') + expect(eventPoster(uri, base).emoji).toBe('๐Ÿ“…') + }) + + it('does not match keywords inside other words', () => { + expect( + eventPoster(uri, {...base, name: 'Gamestop earnings', mode: 'virtual'}) + .emoji, + ).toBe('๐Ÿ’ป') + }) +}) diff --git a/src/features/events/components/EventCard.tsx b/src/features/events/components/EventCard.tsx new file mode 100644 index 000000000..fa26d422c --- /dev/null +++ b/src/features/events/components/EventCard.tsx @@ -0,0 +1,139 @@ +import {useMemo} from 'react' +import {View} from 'react-native' +import {Image} from 'expo-image' +import {AtUri} from '@atproto/api' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import {LinearGradientBackground} from '#/components/LinearGradientBackground' +import {Link} from '#/components/Link' +import {Text} from '#/components/Typography' +import {type EventPhase, eventPhase} from '../format' +import {eventPoster} from '../poster' +import {useEventQuery} from '../queries' +import {coverUrl, parseEventRecord} from '../record' +import {type EventView} from '../types' +import {makeEventLink} from '../url' +import {EventMeta} from './EventMeta' +import {RsvpButtons} from './RsvpButtons' + +export function EventCard({ + event: initial, + badge, + showPhase, + showRsvp = true, +}: { + event: EventView + badge?: string + showPhase?: boolean + showRsvp?: boolean +}) { + const t = useTheme() + const {_} = useLingui() + const {data} = useEventQuery(initial.uri, initial) + const event = data ?? initial + const parsed = useMemo(() => parseEventRecord(event.record), [event.record]) + if (!parsed) return null + const phase = eventPhase(parsed, new Date()) + const cover = coverUrl(event) + const poster = eventPoster(event.uri, parsed) + const href = makeEventLink(event.creator, new AtUri(event.uri).rkey) + + return ( + + + + {cover ? ( + + ) : ( + + {poster.emoji} + + )} + + {(badge || parsed.cancelled || (showPhase && phase)) && ( + + {showPhase && phase && !parsed.cancelled && ( + + )} + {(badge || parsed.cancelled) && ( + + {parsed.cancelled ? Cancelled : badge} + + )} + + )} + + {parsed.name} + + + + + + {showRsvp && !parsed.cancelled && phase !== 'past' && ( + + + + )} + + ) +} + +function PhasePill({phase}: {phase: EventPhase}) { + const t = useTheme() + const current = phase === 'current' + return ( + + + {phase === 'upcoming' ? ( + Upcoming + ) : current ? ( + Happening now + ) : ( + Past + )} + + + ) +} diff --git a/src/features/events/components/EventEmbed.tsx b/src/features/events/components/EventEmbed.tsx new file mode 100644 index 000000000..78e0e530f --- /dev/null +++ b/src/features/events/components/EventEmbed.tsx @@ -0,0 +1,135 @@ +import {useMemo} from 'react' +import {type StyleProp, View, type ViewStyle} from 'react-native' +import {Image} from 'expo-image' +import {type AppBskyEmbedExternal} from '@atproto/api' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {useOpenLink} from '#/lib/hooks/useOpenLink' +import {toNiceDomain} from '#/lib/strings/url-helpers' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import {LinearGradientBackground} from '#/components/LinearGradientBackground' +import {Link} from '#/components/Link' +import {ExternalEmbed} from '#/components/Post/Embed/ExternalEmbed' +import {Text} from '#/components/Typography' +import {eventPhase} from '../format' +import {eventPoster} from '../poster' +import {useEventQuery} from '../queries' +import {coverUrl, parseEventRecord} from '../record' +import {eventAtUri, type EventRef, makeEventLink} from '../url' +import {EventMeta} from './EventMeta' +import {RsvpButtons} from './RsvpButtons' + +export function EventEmbed({ + eventRef, + link, + onOpen, + style, +}: { + eventRef: EventRef + link: AppBskyEmbedExternal.ViewExternal + onOpen?: () => void + style?: StyleProp +}) { + const t = useTheme() + const {_} = useLingui() + const openLink = useOpenLink() + const {data: did} = useResolveDidQuery(eventRef.actor) + const {data: event} = useEventQuery( + did ? eventAtUri(did, eventRef.rkey) : undefined, + ) + const parsed = useMemo( + () => (event ? parseEventRecord(event.record) : undefined), + [event], + ) + + if (!event || !parsed) { + return + } + + const phase = eventPhase(parsed, new Date()) + const cover = coverUrl(event) + const poster = eventPoster(event.uri, parsed) + return ( + + + + {cover ? ( + + ) : ( + + {poster.emoji} + + )} + + {(parsed.cancelled || phase === 'current') && ( + + {parsed.cancelled ? ( + Cancelled + ) : ( + Happening now + )} + + )} + + {parsed.name} + + + + + + {!parsed.cancelled && phase !== 'past' && ( + + {parsed.joinUrl && ( + + )} + + + )} + + ) +} diff --git a/src/features/events/components/EventMeta.tsx b/src/features/events/components/EventMeta.tsx new file mode 100644 index 000000000..ac2207abc --- /dev/null +++ b/src/features/events/components/EventMeta.tsx @@ -0,0 +1,78 @@ +import {View} from 'react-native' +import {msg, plural} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import {AvatarStack} from '#/components/AvatarStack' +import {Clock_Stroke2_Corner0_Rounded as ClockIcon} from '#/components/icons/Clock' +import {Globe_Stroke2_Corner0_Rounded as GlobeIcon} from '#/components/icons/Globe' +import {Pin_Stroke2_Corner0_Rounded as PinIcon} from '#/components/icons/Pin' +import {Text} from '#/components/Typography' +import {formatEventTime} from '../format' +import {type ParsedEvent} from '../record' +import {type EventView} from '../types' + +export function EventMeta({ + event, + parsed, +}: { + event: EventView + parsed: ParsedEvent +}) { + const t = useTheme() + const {_, i18n} = useLingui() + const time = formatEventTime(parsed, i18n.locale) + const place = + parsed.location ?? + (parsed.mode === 'virtual' || parsed.streamplaceUrl + ? _(msg`Online`) + : undefined) + const knownGoing = event.knownGoing ?? [] + + return ( + + {time && ( + + + + {time.primary} + {time.local ? ` ยท ${_(msg`${time.local} your time`)}` : ''} + + + )} + {place && ( + + {parsed.location ? ( + + ) : ( + + )} + + {place} + + + )} + + {knownGoing.length > 0 && ( + + )} + + {event.interestedCount > 0 ? ( + + {plural(event.goingCount, {one: '# going', other: '# going'})} ยท{' '} + {plural(event.interestedCount, { + one: '# interested', + other: '# interested', + })} + + ) : ( + plural(event.goingCount, {one: '# going', other: '# going'}) + )} + + + + ) +} diff --git a/src/features/events/components/ProfileEvents.tsx b/src/features/events/components/ProfileEvents.tsx new file mode 100644 index 000000000..4eb642443 --- /dev/null +++ b/src/features/events/components/ProfileEvents.tsx @@ -0,0 +1,162 @@ +import {useCallback, useEffect, useImperativeHandle, useState} from 'react' +import { + findNodeHandle, + type ListRenderItemInfo, + useWindowDimensions, + View, +} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' + +import {useBottomBarOffset} from '#/lib/hooks/useBottomBarOffset' +import {logger} from '#/logger' +import {useSession} from '#/state/session' +import {EmptyState} from '#/view/com/util/EmptyState' +import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' +import {List, type ListRef} from '#/view/com/util/List' +import {FeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' +import {atoms as a, ios} from '#/alf' +import {CalendarDays_Stroke2_Corner0_Rounded as CalendarIcon} from '#/components/icons/CalendarDays' +import {ListFooter} from '#/components/Lists' +import {IS_IOS} from '#/env' +import {useMyEventsTimeline} from '../queries' +import {type EventView, RSVP_GOING, RSVP_INTERESTED} from '../types' +import {EventCard} from './EventCard' + +interface SectionRef { + scrollToTop: () => void +} + +function keyExtractor(item: EventView) { + return item.uri +} + +export function ProfileEvents({ + ref, + scrollElRef, + headerOffset, + enabled, + setScrollViewTag, +}: { + ref?: React.Ref + scrollElRef: ListRef + headerOffset: number + enabled?: boolean + setScrollViewTag: (tag: number | null) => void +}) { + const {_} = useLingui() + const {currentAccount} = useSession() + const {height} = useWindowDimensions() + const bottomBarOffset = useBottomBarOffset(100) + const [isPTRing, setIsPTRing] = useState(false) + const { + events, + isLoading, + error, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + refetch, + } = useMyEventsTimeline(enabled) + + useImperativeHandle(ref, () => ({ + scrollToTop: () => { + scrollElRef.current?.scrollToOffset({ + animated: true, + offset: -headerOffset, + }) + }, + })) + + useEffect(() => { + if (IS_IOS && enabled && scrollElRef.current) { + setScrollViewTag(findNodeHandle(scrollElRef.current)) + } + }, [enabled, scrollElRef, setScrollViewTag]) + + const onRefresh = useCallback(async () => { + setIsPTRing(true) + try { + await refetch() + } catch (err) { + logger.error('Failed to refresh events', {message: err}) + } + setIsPTRing(false) + }, [refetch]) + + const onEndReached = useCallback(() => { + if (isFetchingNextPage || !hasNextPage || error) return + fetchNextPage().catch(err => + logger.error('Failed to load more events', {message: err}), + ) + }, [isFetchingNextPage, hasNextPage, error, fetchNextPage]) + + const renderItem = useCallback( + ({item}: ListRenderItemInfo) => { + const status = item.viewer?.rsvp?.status + const badge = + item.creator.did === currentAccount?.did + ? _(msg`Hosting`) + : status === RSVP_GOING + ? _(msg`Going`) + : status === RSVP_INTERESTED + ? _(msg`Interested`) + : undefined + return ( + + + + ) + }, + [_, currentAccount?.did], + ) + + return ( + void onRefresh()} + onEndReached={onEndReached} + onEndReachedThreshold={2} + headerOffset={headerOffset} + progressViewOffset={ios(0)} + contentContainerStyle={{ + minHeight: height + headerOffset, + paddingBottom: bottomBarOffset, + }} + desktopFixedHeight + ListEmptyComponent={ + isLoading ? ( + FeedLoadingPlaceholder + ) : error ? ( + void refetch()} + /> + ) : ( + + + + ) + } + ListFooterComponent={ + events.length ? ( + + ) : undefined + } + /> + ) +} diff --git a/src/features/events/components/RsvpButtons.tsx b/src/features/events/components/RsvpButtons.tsx new file mode 100644 index 000000000..ac3d773a6 --- /dev/null +++ b/src/features/events/components/RsvpButtons.tsx @@ -0,0 +1,82 @@ +import {View} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' + +import {logger} from '#/logger' +import {useRequireAuth} from '#/state/session' +import {atoms as a} from '#/alf' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import {Check_Stroke2_Corner0_Rounded as CheckIcon} from '#/components/icons/Check' +import * as Toast from '#/components/Toast' +import {useRsvpMutation} from '../queries' +import { + type EventView, + RSVP_GOING, + RSVP_INTERESTED, + RSVP_NOTGOING, + type RsvpStatus, +} from '../types' + +export function RsvpButtons({ + event, + size = 'small', +}: { + event: EventView + size?: 'small' | 'large' +}) { + const {_} = useLingui() + const requireAuth = useRequireAuth() + const {mutate, isPending} = useRsvpMutation(event) + const current = event.viewer?.rsvp?.status + + const onPress = (status: RsvpStatus) => + requireAuth(() => + mutate( + {status, current: event.viewer?.rsvp}, + { + onError: error => { + logger.error('Failed to update RSVP', {safeMessage: error}) + Toast.show(_(msg`Couldn't update your RSVP`), {type: 'error'}) + }, + }, + ), + ) + + const choices: {status: RsvpStatus; label: string; removeLabel: string}[] = [ + { + status: RSVP_GOING, + label: _(msg`Going`), + removeLabel: _(msg`Going, tap to remove`), + }, + { + status: RSVP_INTERESTED, + label: _(msg`Interested`), + removeLabel: _(msg`Interested, tap to remove`), + }, + { + status: RSVP_NOTGOING, + label: _(msg`Not going`), + removeLabel: _(msg`Not going, tap to remove`), + }, + ] + return ( + + {choices.map(choice => { + const selected = current === choice.status + return ( + + ) + })} + + ) +} diff --git a/src/features/events/format.ts b/src/features/events/format.ts new file mode 100644 index 000000000..cedf838bd --- /dev/null +++ b/src/features/events/format.ts @@ -0,0 +1,85 @@ +import {type ParsedEvent} from './record' + +const format = (date: Date, locale: string, timeZone?: string) => + new Intl.DateTimeFormat(locale, { + weekday: 'short', + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + timeZoneName: 'short', + timeZone, + }).format(date) + +/** + * The start time in the event's own timezone, plus the viewer's local time + * when that differs, so an in-person event reads the way the host wrote it. + */ +export function formatEventTime( + event: ParsedEvent, + locale: string, +): {primary: string; local?: string} | undefined { + if (!event.startsAt) return + const local = format(event.startsAt, locale) + if (!event.timezone) return {primary: local} + const inEventZone = format(event.startsAt, locale, event.timezone) + return inEventZone === local + ? {primary: local} + : {primary: inEventZone, local} +} + +export type EventPhase = 'upcoming' | 'current' | 'past' + +// Most events don't publish an end time; treat them as running this long. +const ASSUMED_DURATION_MS = 4 * 60 * 60 * 1000 + +export function eventPhase( + event: ParsedEvent, + now: Date, +): EventPhase | undefined { + if (!event.startsAt) return + if (now < event.startsAt) return 'upcoming' + const end = + event.endsAt ?? new Date(event.startsAt.getTime() + ASSUMED_DURATION_MS) + return now < end ? 'current' : 'past' +} + +export type EventDateParts = { + month: string + day: string + longDate: string + timeRange: string +} + +/** Date pieces for large date displays, in the event's own timezone. */ +export function eventDateParts( + event: ParsedEvent, + locale: string, +): EventDateParts | undefined { + if (!event.startsAt) return + const timeZone = event.timezone + const part = (options: Intl.DateTimeFormatOptions, date: Date) => + new Intl.DateTimeFormat(locale, {...options, timeZone}).format(date) + const time = {hour: 'numeric', minute: '2-digit'} as const + const start = part(time, event.startsAt) + const zone = part({timeZoneName: 'short'}, event.startsAt).split(' ').pop() + const dayKey = (date: Date) => + part({year: 'numeric', month: 'numeric', day: 'numeric'}, date) + const end = !event.endsAt + ? undefined + : dayKey(event.endsAt) === dayKey(event.startsAt) + ? part(time, event.endsAt) + : part( + {weekday: 'short', month: 'short', day: 'numeric', ...time}, + event.endsAt, + ) + return { + month: part({month: 'short'}, event.startsAt).toUpperCase(), + day: part({day: 'numeric'}, event.startsAt), + longDate: part( + {weekday: 'long', month: 'long', day: 'numeric'}, + event.startsAt, + ), + timeRange: `${end ? `${start} โ€“ ${end}` : start} ${zone ?? ''}`.trim(), + } +} diff --git a/src/features/events/poster.ts b/src/features/events/poster.ts new file mode 100644 index 000000000..f70a8cbb0 --- /dev/null +++ b/src/features/events/poster.ts @@ -0,0 +1,66 @@ +import {type gradients} from '#/alf/tokens' +import {type ParsedEvent} from './record' + +const GRADIENTS: (keyof typeof gradients)[] = [ + 'primary', + 'sky', + 'midnight', + 'sunrise', + 'sunset', + 'summer', + 'nordic', + 'bonfire', +] + +const KEYWORDS: [RegExp, string][] = [ + [/\b(open mic|karaoke|poetry slam|spoken word)\b/i, '๐ŸŽค'], + [/\b(party|parties|birthday|celebration|launch|mixer)\b/i, '๐ŸŽ‰'], + [/\b(music|dj|concert|gig|band|jam|listening|album)\b/i, '๐ŸŽถ'], + [/\b(film|films|movie|movies|screening|cinema)\b/i, '๐ŸŽฌ'], + [/\b(book|books|reading|library|writing)\b/i, '๐Ÿ“š'], + [ + /\b(brunch|breakfast|lunch|dinner|potluck|cookout|bbq|barbecue|picnic|food)\b/i, + '๐Ÿฝ๏ธ', + ], + [/\b(coffee|tea)\b/i, 'โ˜•'], + [/\b(run|running|walk|hike|yoga|workout|fitness|bike|ride)\b/i, '๐Ÿƒ'], + [/\b(game|games|gaming|trivia|tournament)\b/i, '๐ŸŽฎ'], + [/\b(art|gallery|exhibit|exhibition|museum|craft|crafts)\b/i, '๐ŸŽจ'], + [/\b(dance|dancing)\b/i, '๐Ÿ’ƒ'], + [/\b(workshop|class|talk|lecture|panel|conference|study)\b/i, '๐ŸŽ“'], + [ + /\b(meeting|meetup|wg|working group|standup|sync|office hours|town hall|call)\b/i, + '๐Ÿ’ฌ', + ], + [/\b(protest|rally|march|vigil)\b/i, 'โœŠ'], +] + +function hash(str: string) { + let h = 0x811c9dc5 + for (let i = 0; i < str.length; i++) { + h ^= str.charCodeAt(i) + h = Math.imul(h, 0x01000193) + } + return h >>> 0 +} + +function pickEmoji(event: ParsedEvent) { + for (const text of [event.name, event.description]) { + if (!text) continue + const match = KEYWORDS.find(([re]) => re.test(text)) + if (match) return match[1] + } + if (event.streamplaceUrl) return '๐Ÿ“บ' + if (event.mode === 'virtual') return '๐Ÿ’ป' + if (event.mode === 'hybrid') return '๐ŸŒ' + if (event.mode === 'inperson') return '๐Ÿ“' + return '๐Ÿ“…' +} + +/** The stand-in poster for an event with no cover. */ +export function eventPoster(uri: string, event: ParsedEvent) { + return { + gradient: GRADIENTS[hash(uri) % GRADIENTS.length], + emoji: pickEmoji(event), + } +} diff --git a/src/features/events/queries.ts b/src/features/events/queries.ts new file mode 100644 index 000000000..fbe458a29 --- /dev/null +++ b/src/features/events/queries.ts @@ -0,0 +1,256 @@ +import {AtUri, type BskyAgent} from '@atproto/api' +import { + type InfiniteData, + type QueryClient, + useInfiniteQuery, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' + +import {communityXrpc} from '#/lib/api/community' +import {STALE} from '#/state/queries' +import {useAgent, useSession} from '#/state/session' +import {applyRsvp} from './rsvp-state' +import {mergeEventTimeline} from './timeline' +import { + type EventView, + RSVP_COLLECTION, + type RsvpStatus, + type RsvpView, +} from './types' + +const EVENT_RQKEY_ROOT = 'calendar-event' +export const EVENT_RQKEY = (uri: string) => [EVENT_RQKEY_ROOT, uri] +const RSVPS_RQKEY_ROOT = 'calendar-event-rsvps' +const RSVPS_RQKEY = (uri: string, status: string, section: string) => [ + RSVPS_RQKEY_ROOT, + uri, + status, + section, +] +const MY_EVENTS_RQKEY_ROOT = 'calendar-my-events' + +async function xrpcJson( + agent: BskyAgent, + method: string, + params: Record, +): Promise { + const res = await communityXrpc(agent, method, {params}) + if (!res.ok) throw new Error(`${method} failed: ${res.status}`) + return (await res.json()) as T +} + +export async function fetchEvents( + agent: BskyAgent, + uris: string[], +): Promise { + const {events} = await xrpcJson<{events: EventView[]}>( + agent, + 'community.blacksky.calendar.getEvents', + {uris}, + ) + return events +} + +export function useEventQuery(uri: string | undefined, initial?: EventView) { + const agent = useAgent() + return useQuery({ + queryKey: EVENT_RQKEY(uri ?? ''), + enabled: !!uri, + staleTime: STALE.SECONDS.THIRTY, + initialData: initial, + queryFn: async () => { + const events = await fetchEvents(agent, [uri!]) + return events[0] ?? null + }, + }) +} + +type RsvpPage = { + rsvps: RsvpView[] + cursor?: string + mutedOrBlockedCount?: number +} + +export function useEventRsvpsQuery( + uri: string | undefined, + status: RsvpStatus | undefined, + section: 'main' | 'mutedOrBlocked' = 'main', + enabled = true, +) { + const agent = useAgent() + return useInfiniteQuery< + RsvpPage, + Error, + InfiniteData, + string[], + string | undefined + >({ + queryKey: RSVPS_RQKEY(uri ?? '', status ?? 'all', section), + enabled: !!uri && enabled, + staleTime: STALE.SECONDS.THIRTY, + initialPageParam: undefined, + getNextPageParam: page => page.cursor, + queryFn: ({pageParam}) => + xrpcJson(agent, 'community.blacksky.calendar.getEventRsvps', { + event: uri!, + status, + section, + limit: 50, + cursor: pageParam, + }), + }) +} + +type MyEventsPage = {events: EventView[]; cursor?: string} + +export function useMyEventsQuery(when: 'upcoming' | 'past', enabled = true) { + const agent = useAgent() + const queryClient = useQueryClient() + const {currentAccount} = useSession() + return useInfiniteQuery< + MyEventsPage, + Error, + InfiniteData, + string[], + string | undefined + >({ + queryKey: [MY_EVENTS_RQKEY_ROOT, currentAccount?.did ?? '', when], + enabled: !!currentAccount && enabled, + staleTime: STALE.SECONDS.THIRTY, + initialPageParam: undefined, + getNextPageParam: page => page.cursor, + queryFn: async ({pageParam}) => { + const page = await xrpcJson( + agent, + 'community.blacksky.calendar.getMyEvents', + {when, limit: 25, cursor: pageParam}, + ) + for (const event of page.events) { + // A cached entry may hold an RSVP the AppView hasn't indexed yet. + if (queryClient.getQueryData(EVENT_RQKEY(event.uri)) === undefined) { + queryClient.setQueryData(EVENT_RQKEY(event.uri), event) + } + } + return page + }, + }) +} + +/** + * The signed-in viewer's events as one list. Upcoming pages are fetched to the + * end before past ones, so the list only ever grows at the bottom. + */ +export function useMyEventsTimeline(enabled = true) { + const upcoming = useMyEventsQuery('upcoming', enabled) + const past = useMyEventsQuery( + 'past', + enabled && upcoming.isSuccess && !upcoming.hasNextPage, + ) + const events = mergeEventTimeline( + upcoming.data?.pages.flatMap(page => page.events) ?? [], + past.data?.pages.flatMap(page => page.events) ?? [], + new Date(), + ) + const next = upcoming.hasNextPage ? upcoming : past + return { + events, + isLoading: upcoming.isLoading || past.isLoading, + error: upcoming.error ?? past.error, + hasNextPage: upcoming.hasNextPage || past.hasNextPage, + isFetchingNextPage: upcoming.isFetchingNextPage || past.isFetchingNextPage, + fetchNextPage: () => next.fetchNextPage(), + refetch: () => Promise.all([upcoming.refetch(), past.refetch()]), + } +} + +function markListsStale(queryClient: QueryClient, uri: string) { + void queryClient.invalidateQueries({ + queryKey: [RSVPS_RQKEY_ROOT, uri], + refetchType: 'none', + }) + void queryClient.invalidateQueries({ + queryKey: [MY_EVENTS_RQKEY_ROOT], + refetchType: 'none', + }) +} + +export type RsvpChange = { + status: RsvpStatus + current?: {uri: string; status: string} +} + +/** + * Pressing the current status again removes the RSVP. `current` must be the + * RSVP as rendered before the press: the optimistic update overwrites the + * cached one. The PDS result is written through without refetching, since + * the AppView lags the write. + */ +export function useRsvpMutation(event: EventView) { + const agent = useAgent() + const queryClient = useQueryClient() + const {currentAccount} = useSession() + const queryKey = EVENT_RQKEY(event.uri) + + return useMutation< + {uri: string; status: RsvpStatus} | undefined, + Error, + RsvpChange, + {prev?: EventView | null} + >({ + mutationFn: async ({status, current}) => { + if (!currentAccount) throw new Error('Not signed in') + const repo = currentAccount.did + if (current && current.status === status) { + await agent.com.atproto.repo.deleteRecord({ + repo, + collection: RSVP_COLLECTION, + rkey: new AtUri(current.uri).rkey, + }) + return undefined + } + const record = { + $type: RSVP_COLLECTION, + subject: {uri: event.uri, cid: event.cid}, + status, + } + if (current) { + const res = await agent.com.atproto.repo.putRecord({ + repo, + collection: RSVP_COLLECTION, + rkey: new AtUri(current.uri).rkey, + record, + }) + return {uri: res.data.uri, status} + } + const res = await agent.com.atproto.repo.createRecord({ + repo, + collection: RSVP_COLLECTION, + record, + }) + return {uri: res.data.uri, status} + }, + onMutate: async ({status, current}) => { + await queryClient.cancelQueries({queryKey}) + const prev = queryClient.getQueryData(queryKey) + const next = + current?.status === status + ? undefined + : {uri: current?.uri ?? 'pending', status} + queryClient.setQueryData(queryKey, applyRsvp(prev ?? event, next)) + return {prev} + }, + onError: (_error, _change, context) => { + queryClient.setQueryData(queryKey, context?.prev ?? event) + }, + onSuccess: result => { + const base = queryClient.getQueryData(queryKey) ?? event + queryClient.setQueryData(queryKey, { + ...base, + viewer: {...base.viewer, rsvp: result}, + }) + markListsStale(queryClient, event.uri) + }, + }) +} diff --git a/src/features/events/record.ts b/src/features/events/record.ts new file mode 100644 index 000000000..8192c9876 --- /dev/null +++ b/src/features/events/record.ts @@ -0,0 +1,154 @@ +import {type ComAtprotoLabelDefs} from '@atproto/api' + +export type EventMode = 'inperson' | 'virtual' | 'hybrid' + +export type EventLink = {uri: string; name?: string} + +export type ParsedEvent = { + name: string + description?: string + startsAt?: Date + endsAt?: Date + timezone?: string + mode?: EventMode + cancelled: boolean + location?: string + links: EventLink[] + streamplaceUrl?: string + joinUrl?: string +} + +const MODE_PREFIX = 'community.lexicon.calendar.event#' + +const asRecord = (value: unknown): Record | undefined => + value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : undefined + +const asString = (value: unknown): string | undefined => + typeof value === 'string' && value.length > 0 ? value : undefined + +const asDate = (value: unknown): Date | undefined => { + const str = asString(value) + if (!str) return + const date = new Date(str) + return isNaN(date.getTime()) ? undefined : date +} + +const isTimezone = (value: string) => { + try { + new Intl.DateTimeFormat('en-US', {timeZone: value}) + return true + } catch { + return false + } +} + +const asWebUrl = (value: unknown): string | undefined => { + const str = asString(value) + if (!str) return + try { + const {protocol} = new URL(str) + return protocol === 'http:' || protocol === 'https:' ? str : undefined + } catch { + return + } +} + +export function isStreamplaceUrl(uri: string): boolean { + try { + const {hostname} = new URL(uri) + return hostname === 'stream.place' || hostname === 'www.stream.place' + } catch { + return false + } +} + +function describeLocation(value: unknown): string | undefined { + const loc = asRecord(value) + if (!loc) return + const name = asString(loc.name) + const parts = [ + asString(loc.street), + asString(loc.locality), + asString(loc.region), + ].filter(Boolean) + if (name && parts.length) return `${name}, ${parts.join(', ')}` + if (name) return name + if (parts.length) return parts.join(', ') + return asString(loc.country) +} + +// Events come from many apps, so every field outside `name` is optional and +// malformed values are dropped rather than failing the whole event. +export function parseEventRecord(record: unknown): ParsedEvent | undefined { + const rec = asRecord(record) + const name = asString(rec?.name) + if (!rec || !name) return + + const links: EventLink[] = [] + if (Array.isArray(rec.uris)) { + for (const item of rec.uris) { + const link = asRecord(item) + const uri = asWebUrl(link?.uri) + if (uri) links.push({uri, name: asString(link?.name)}) + } + } + const locationLinks: EventLink[] = [] + let location: string | undefined + if (Array.isArray(rec.locations)) { + for (const item of rec.locations) { + const loc = asRecord(item) + if (loc && 'uri' in loc) { + const uri = asWebUrl(loc.uri) + if (uri) locationLinks.push({uri, name: asString(loc?.name)}) + } else if (!location) { + location = describeLocation(loc) + } + } + } + + links.push(...locationLinks) + + const rawMode = asString(rec.mode)?.replace(MODE_PREFIX, '') + const mode = + rawMode === 'inperson' || rawMode === 'virtual' || rawMode === 'hybrid' + ? rawMode + : undefined + const timezone = asString(rec.timezone) + return { + name, + description: asString(rec.description), + startsAt: asDate(rec.startsAt), + endsAt: asDate(rec.endsAt), + timezone: timezone && isTimezone(timezone) ? timezone : undefined, + mode, + cancelled: asString(rec.status) === `${MODE_PREFIX}cancelled`, + location, + links, + streamplaceUrl: links.find(link => isStreamplaceUrl(link.uri))?.uri, + joinUrl: + mode === 'virtual' || mode === 'hybrid' + ? [...locationLinks, ...links].find(link => !isStreamplaceUrl(link.uri)) + ?.uri + : undefined, + } +} + +const HIDE_COVER_LABELS = new Set([ + '!hide', + '!warn', + 'porn', + 'sexual', + 'nudity', + 'graphic-media', + 'gore', +]) + +export function coverUrl(event: { + thumb?: string + labels?: ComAtprotoLabelDefs.Label[] +}): string | undefined { + if (event.labels?.some(label => HIDE_COVER_LABELS.has(label.val))) return + return event.thumb +} diff --git a/src/features/events/rsvp-state.ts b/src/features/events/rsvp-state.ts new file mode 100644 index 000000000..2aaff837f --- /dev/null +++ b/src/features/events/rsvp-state.ts @@ -0,0 +1,26 @@ +import { + type EventView, + RSVP_GOING, + RSVP_INTERESTED, + type RsvpStatus, +} from './types' + +const countKey = (status: string | undefined) => + status === RSVP_GOING + ? 'goingCount' + : status === RSVP_INTERESTED + ? 'interestedCount' + : undefined + +export function applyRsvp( + event: EventView, + next: {uri: string; status: RsvpStatus} | undefined, +): EventView { + const updated = {...event} + const prevKey = countKey(event.viewer?.rsvp?.status) + const nextKey = countKey(next?.status) + if (prevKey) updated[prevKey] = Math.max(0, updated[prevKey] - 1) + if (nextKey) updated[nextKey] = updated[nextKey] + 1 + updated.viewer = {...event.viewer, rsvp: next} + return updated +} diff --git a/src/features/events/timeline.ts b/src/features/events/timeline.ts new file mode 100644 index 000000000..d7be9f038 --- /dev/null +++ b/src/features/events/timeline.ts @@ -0,0 +1,31 @@ +import {eventPhase} from './format' +import {parseEventRecord} from './record' +import {type EventView} from './types' + +/** + * One list out of the upcoming (soonest first) and past (latest first) pages: + * events happening now lead, then upcoming, then past. Happening-now events + * have already started, so they arrive with the past pages. + */ +export function mergeEventTimeline( + upcoming: EventView[], + past: EventView[], + now: Date, +): EventView[] { + const current: EventView[] = [] + const finished: EventView[] = [] + for (const event of past) { + const parsed = parseEventRecord(event.record) + if (parsed && eventPhase(parsed, now) === 'current') { + current.push(event) + } else { + finished.push(event) + } + } + const seen = new Set() + return [...current, ...upcoming, ...finished].filter(event => { + if (seen.has(event.uri)) return false + seen.add(event.uri) + return true + }) +} diff --git a/src/features/events/types.ts b/src/features/events/types.ts new file mode 100644 index 000000000..bd8fd6642 --- /dev/null +++ b/src/features/events/types.ts @@ -0,0 +1,34 @@ +import {type AppBskyActorDefs, type ComAtprotoLabelDefs} from '@atproto/api' + +export const EVENT_COLLECTION = 'community.lexicon.calendar.event' +export const RSVP_COLLECTION = 'community.lexicon.calendar.rsvp' + +export const RSVP_GOING = 'community.lexicon.calendar.rsvp#going' +export const RSVP_INTERESTED = 'community.lexicon.calendar.rsvp#interested' +export const RSVP_NOTGOING = 'community.lexicon.calendar.rsvp#notgoing' + +export type RsvpStatus = + | typeof RSVP_GOING + | typeof RSVP_INTERESTED + | typeof RSVP_NOTGOING + +export type EventView = { + uri: string + cid: string + creator: AppBskyActorDefs.ProfileViewBasic + record: unknown + thumb?: string + goingCount: number + interestedCount: number + knownGoing?: AppBskyActorDefs.ProfileViewBasic[] + viewer?: {rsvp?: {uri: string; status: string}} + labels?: ComAtprotoLabelDefs.Label[] + indexedAt: string +} + +export type RsvpView = { + uri: string + status: string + actor: AppBskyActorDefs.ProfileViewBasic + indexedAt: string +} diff --git a/src/features/events/url.ts b/src/features/events/url.ts new file mode 100644 index 000000000..050612b20 --- /dev/null +++ b/src/features/events/url.ts @@ -0,0 +1,77 @@ +import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext' +import {EVENT_COLLECTION} from './types' + +export type EventRef = {actor: string; rkey: string} + +const RKEY_RE = /^[a-zA-Z0-9._:~-]{1,512}$/ + +const hostOf = (url: string) => { + try { + return new URL(url).hostname + } catch { + return + } +} + +const blackskyHosts = () => { + const main = hostOf(DEFAULT_BRAND_CONFIG.web.domains.main) + return main ? [main, `staging.${main}`] : [] +} + +// Recognises event links from Blacksky and from other atproto event apps so +// they all render as the same card. +export function parseEventUrl( + url: string, + brandDomains: string[] = [], +): EventRef | undefined { + let urlp: URL + try { + urlp = new URL(url) + } catch { + return + } + const host = urlp.hostname.replace(/^www\./, '') + const ownHosts = new Set([ + ...blackskyHosts(), + ...brandDomains.map(hostOf).filter((h): h is string => !!h), + ]) + const isOwn = ownHosts.has(host) + if (!isOwn && host !== 'atmo.rsvp' && host !== 'smokesignal.events') return + let parts: string[] + try { + parts = urlp.pathname.split('/').filter(Boolean).map(decodeURIComponent) + } catch { + return + } + let ref: EventRef | undefined + if (isOwn && parts.length === 3 && parts[0] === 'event') { + ref = {actor: parts[1], rkey: parts[2]} + } else if ( + host === 'atmo.rsvp' && + parts.length >= 4 && + parts[0] === 'p' && + parts[2] === 'e' + ) { + ref = {actor: parts[1], rkey: parts[3]} + } else if (host === 'smokesignal.events' && parts.length === 2) { + ref = {actor: parts[0], rkey: parts[1]} + } + if (!ref || !RKEY_RE.test(ref.rkey)) return + if (!ref.actor.startsWith('did:') && !ref.actor.includes('.')) return + return ref +} + +export function eventAtUri(did: string, rkey: string) { + return `at://${did}/${EVENT_COLLECTION}/${rkey}` +} + +export function makeEventLink( + creator: {did: string; handle?: string}, + rkey: string, +) { + const actor = + creator.handle && creator.handle !== 'handle.invalid' + ? creator.handle + : creator.did + return `/event/${actor}/${rkey}` +} diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index 3c57c0f9e..1876c8bd6 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -9,6 +9,7 @@ export type CommonNavigatorParams = { NotFound: undefined AuthCallback: undefined Lists: undefined + Event: {name: string; rkey: string} Moderation: undefined ModerationModlists: undefined ModerationMutedAccounts: undefined diff --git a/src/routes.ts b/src/routes.ts index d218fc06d..a2ae038ac 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -16,6 +16,7 @@ export const router = new Router({ LegacyNotificationSettings: '/notifications/settings', Settings: '/settings', Lists: '/lists', + Event: '/event/:name/:rkey', // moderation Moderation: '/moderation', ModerationModlists: '/moderation/modlists', diff --git a/src/screens/Event/EventHeader.tsx b/src/screens/Event/EventHeader.tsx new file mode 100644 index 000000000..5f1882275 --- /dev/null +++ b/src/screens/Event/EventHeader.tsx @@ -0,0 +1,385 @@ +import {View} from 'react-native' +import {Image} from 'expo-image' +import {msg, plural} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {useOpenLink} from '#/lib/hooks/useOpenLink' +import {toNiceDomain} from '#/lib/strings/url-helpers' +import {logger} from '#/logger' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {useRequireAuth} from '#/state/session' +import {UserAvatar} from '#/view/com/util/UserAvatar' +import {atoms as a, useTheme} from '#/alf' +import {AvatarStack} from '#/components/AvatarStack' +import {Button, ButtonText} from '#/components/Button' +import {LinearGradientBackground} from '#/components/LinearGradientBackground' +import {InlineLinkText} from '#/components/Link' +import * as ProfileCard from '#/components/ProfileCard' +import * as Toast from '#/components/Toast' +import {Text} from '#/components/Typography' +import { + eventDateParts, + eventPhase, + formatEventTime, +} from '#/features/events/format' +import {eventPoster} from '#/features/events/poster' +import {useRsvpMutation} from '#/features/events/queries' +import {coverUrl, type ParsedEvent} from '#/features/events/record' +import { + type EventView, + RSVP_GOING, + RSVP_INTERESTED, + RSVP_NOTGOING, + type RsvpStatus, + type RsvpView, +} from '#/features/events/types' + +export function EventHeader({ + event, + parsed, + guests, +}: { + event: EventView + parsed: ParsedEvent + guests: RsvpView[] +}) { + const t = useTheme() + const {_, i18n} = useLingui() + const openLink = useOpenLink() + const date = eventDateParts(parsed, i18n.locale) + const localTime = formatEventTime(parsed, i18n.locale)?.local + const past = eventPhase(parsed, new Date()) === 'past' + const otherLinks = parsed.links.filter( + link => link.uri !== parsed.joinUrl && link.uri !== parsed.streamplaceUrl, + ) + const place = + parsed.location ?? + (parsed.streamplaceUrl || parsed.mode === 'virtual' + ? _(msg`Online`) + : undefined) + + return ( + + + + {parsed.cancelled && ( + + + Cancelled + + + )} + + + {parsed.name} + + {date && ( + + + {date.longDate} + + + {date.timeRange} + + {localTime && ( + + {localTime} your time + + )} + + )} + {place && ( + + ๐Ÿ“ {place} + + )} + {parsed.joinUrl && !parsed.cancelled && !past && ( + + )} + + + + + Hosted by{' '} + + {event.creator.displayName || `@${event.creator.handle}`} + + + + + {parsed.streamplaceUrl && ( + + )} + {!parsed.cancelled && !past && } + + + {parsed.description && ( + + + About + + {parsed.description} + + )} + {otherLinks.length > 0 && ( + + + Links + + {otherLinks.map(link => ( + + {link.name || toNiceDomain(link.uri)} + + ))} + + )} + + Guest list + + + ) +} + +function Poster({event, parsed}: {event: EventView; parsed: ParsedEvent}) { + const size = 280 + const cover = coverUrl(event) + if (cover) { + return ( + + ) + } + const poster = eventPoster(event.uri, parsed) + return ( + + {poster.emoji} + + ) +} + +function RsvpChoices({event}: {event: EventView}) { + const t = useTheme() + const {_} = useLingui() + const requireAuth = useRequireAuth() + const {mutate, isPending} = useRsvpMutation(event) + const current = event.viewer?.rsvp?.status + const choices: { + status: RsvpStatus + emoji: string + label: string + removeLabel: string + }[] = [ + { + status: RSVP_GOING, + emoji: '๐Ÿ‘', + label: _(msg`Going`), + removeLabel: _(msg`Going, tap to remove`), + }, + { + status: RSVP_INTERESTED, + emoji: '๐Ÿค”', + label: _(msg`Interested`), + removeLabel: _(msg`Interested, tap to remove`), + }, + { + status: RSVP_NOTGOING, + emoji: '๐Ÿ˜ข', + label: _(msg`Not going`), + removeLabel: _(msg`Not going, tap to remove`), + }, + ] + const onPress = (status: RsvpStatus) => + requireAuth(() => + mutate( + {status, current: event.viewer?.rsvp}, + { + onError: error => { + logger.error('Failed to update RSVP', {safeMessage: error}) + Toast.show(_(msg`Couldn't update your RSVP`), {type: 'error'}) + }, + }, + ), + ) + + return ( + + {choices.map(choice => { + const selected = current === choice.status + return ( + + ) + })} + + ) +} + +function Guests({event, guests}: {event: EventView; guests: RsvpView[]}) { + const t = useTheme() + if (event.goingCount + event.interestedCount === 0) return null + return ( + + {guests.length > 0 && ( + guest.actor)} + size={28} + /> + )} + + {plural(event.goingCount, {one: '# going', other: '# going'})} + {event.interestedCount > 0 + ? ` ยท ${plural(event.interestedCount, { + one: '# interested', + other: '# interested', + })}` + : ''} + + + ) +} + +export function GuestRow({ + rsvp, + noBorder, +}: { + rsvp: RsvpView + noBorder?: boolean +}) { + const t = useTheme() + const {_} = useLingui() + const moderationOpts = useModerationOpts() + if (!moderationOpts) return null + const response = + rsvp.status === RSVP_GOING + ? {emoji: '๐Ÿ‘', label: _(msg`Going`)} + : rsvp.status === RSVP_INTERESTED + ? {emoji: '๐Ÿค”', label: _(msg`Interested`)} + : {emoji: '๐Ÿ˜ข', label: _(msg`Not going`)} + + return ( + + + + + + + + {response.emoji} + + {response.label} + + + + + + + ) +} diff --git a/src/screens/Event/EventScreen.tsx b/src/screens/Event/EventScreen.tsx new file mode 100644 index 000000000..821e52381 --- /dev/null +++ b/src/screens/Event/EventScreen.tsx @@ -0,0 +1,183 @@ +import {useCallback, useMemo, useState} from 'react' +import {View} from 'react-native' +import {msg, plural} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import { + type CommonNavigatorParams, + type NativeStackScreenProps, +} from '#/lib/routes/types' +import {cleanError} from '#/lib/strings/errors' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' +import {List} from '#/view/com/util/List' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import * as Layout from '#/components/Layout' +import {ListFooter, ListMaybePlaceholder} from '#/components/Lists' +import {Text} from '#/components/Typography' +import {useEventQuery, useEventRsvpsQuery} from '#/features/events/queries' +import {type ParsedEvent, parseEventRecord} from '#/features/events/record' +import { + type EventView, + RSVP_GOING, + type RsvpView, +} from '#/features/events/types' +import {eventAtUri} from '#/features/events/url' +import {EventHeader, GuestRow} from './EventHeader' + +type Props = NativeStackScreenProps + +export function EventScreen({route}: Props) { + const {_} = useLingui() + const {name, rkey} = route.params + const {data: did, error: resolveError} = useResolveDidQuery(name) + const uri = did ? eventAtUri(did, rkey) : undefined + const {data: event, isLoading, error, refetch} = useEventQuery(uri) + const parsed = useMemo( + () => (event ? parseEventRecord(event.record) : undefined), + [event], + ) + + return ( + + + + + + Event + + + + + {event && parsed ? ( + + ) : ( + + )} + + ) +} + +function EventBody({event, parsed}: {event: EventView; parsed: ParsedEvent}) { + const {_} = useLingui() + const { + data, + refetch, + isLoading, + error, + fetchNextPage, + hasNextPage, + isFetchingNextPage, + } = useEventRsvpsQuery(event.uri, undefined) + const rsvps = useMemo( + () => data?.pages.flatMap(page => page.rsvps) ?? [], + [data], + ) + const going = rsvps.filter(rsvp => rsvp.status === RSVP_GOING) + const mutedOrBlockedCount = data?.pages[0]?.mutedOrBlockedCount ?? 0 + + const renderItem = useCallback( + ({item, index}: {item: RsvpView; index: number}) => ( + + ), + [], + ) + + return ( + item.uri} + renderItem={renderItem} + ListHeaderComponent={ + + + {!isLoading && + !error && + event.goingCount + event.interestedCount === 0 && ( + + No one has RSVP'd yet. + + )} + + } + onEndReached={() => { + if (hasNextPage && !isFetchingNextPage) void fetchNextPage() + }} + onEndReachedThreshold={2} + ListFooterComponent={ + + + {mutedOrBlockedCount > 0 && ( + + )} + + } + sideBorders={false} + /> + ) +} + +function MutedOrBlockedSection({ + eventUri, + count, +}: { + eventUri: string + count: number +}) { + const t = useTheme() + const {_} = useLingui() + const [open, setOpen] = useState(false) + const {data} = useEventRsvpsQuery(eventUri, undefined, 'mutedOrBlocked', open) + const rsvps = data?.pages.flatMap(page => page.rsvps) ?? [] + + return ( + + + {open && + rsvps.map((item, index) => ( + + ))} + + ) +} diff --git a/src/view/screens/Profile.tsx b/src/view/screens/Profile.tsx index 5b703f67a..27cc685bf 100644 --- a/src/view/screens/Profile.tsx +++ b/src/view/screens/Profile.tsx @@ -55,6 +55,8 @@ import {VideoClip_Stroke1_Corner0_Rounded as VideoIcon} from '#/components/icons import * as Layout from '#/components/Layout' import {ScreenHider} from '#/components/moderation/ScreenHider' import {ProfileStarterPacks} from '#/components/StarterPack/ProfileStarterPacks' +import {useAnalytics} from '#/analytics' +import {ProfileEvents} from '#/features/events/components/ProfileEvents' import {navigate} from '#/Navigation' import {ExpoScrollForwarderView} from '../../../modules/expo-scroll-forwarder' @@ -214,6 +216,7 @@ function ProfileScreenLoaded({ }) const [currentPage, setCurrentPage] = useState(0) const {_} = useLingui() + const ax = useAnalytics() const [scrollViewTag, setScrollViewTag] = useState(null) @@ -223,6 +226,7 @@ function ProfileScreenLoaded({ const mediaSectionRef = useRef(null) const videosSectionRef = useRef(null) const likesSectionRef = useRef(null) + const eventsSectionRef = useRef(null) const feedsSectionRef = useRef(null) const listsSectionRef = useRef(null) const starterPacksSectionRef = useRef(null) @@ -250,6 +254,7 @@ function ProfileScreenLoaded({ const showMediaTab = !hasLabeler const showVideosTab = !hasLabeler const showLikesTab = isMe + const showEventsTab = isMe && ax.features.enabled(ax.features.EventsEnable) const feedGenCount = profile.associated?.feedgens || 0 const showFeedsTab = isMe || feedGenCount > 0 const starterPackCount = profile.associated?.starterPacks || 0 @@ -267,6 +272,7 @@ function ProfileScreenLoaded({ showMediaTab ? _(msg`Media`) : undefined, showVideosTab ? _(msg`Videos`) : undefined, showLikesTab ? _(msg`Likes`) : undefined, + showEventsTab ? _(msg`Events`) : undefined, showFeedsTab ? _(msg`Feeds`) : undefined, showStarterPacksTab ? _(msg`Starter Packs`) : undefined, showListsTab && !hasLabeler ? _(msg`Lists`) : undefined, @@ -280,6 +286,7 @@ function ProfileScreenLoaded({ let mediaIndex: number | null = null let videosIndex: number | null = null let likesIndex: number | null = null + let eventsIndex: number | null = null let feedsIndex: number | null = null let starterPacksIndex: number | null = null let listsIndex: number | null = null @@ -304,6 +311,9 @@ function ProfileScreenLoaded({ if (showLikesTab) { likesIndex = nextIndex++ } + if (showEventsTab) { + eventsIndex = nextIndex++ + } if (showFeedsTab) { feedsIndex = nextIndex++ } @@ -330,6 +340,8 @@ function ProfileScreenLoaded({ videosSectionRef.current?.scrollToTop() } else if (index === likesIndex) { likesSectionRef.current?.scrollToTop() + } else if (index === eventsIndex) { + eventsSectionRef.current?.scrollToTop() } else if (index === feedsIndex) { feedsSectionRef.current?.scrollToTop() } else if (index === starterPacksIndex) { @@ -346,6 +358,7 @@ function ProfileScreenLoaded({ mediaIndex, videosIndex, likesIndex, + eventsIndex, feedsIndex, listsIndex, starterPacksIndex, @@ -577,6 +590,17 @@ function ProfileScreenLoaded({ /> ) : null} + {showEventsTab + ? ({headerHeight, isFocused, scrollElRef}) => ( + + ) + : null} {showFeedsTab ? ({headerHeight, isFocused, scrollElRef}) => (