diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 38331e661..27a7b26f5 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -364,6 +364,8 @@ export type Events = { 'composer:poll:open': {} 'composer:poll:remove': {} 'composer:poll:statementAdd': {count: number} + 'composer:event:open': {} + 'composer:event:remove': {} 'composer:image:edit': { platform: Platform['OS'] } @@ -1216,6 +1218,12 @@ export type Events = { 'share:press:recentDm': {} 'share:press:embed': {} + 'event:create': { + uri: string + hasDescription: boolean + hasLocation: boolean + hasCover: boolean + } 'assembly:create': { conversationId: string statementCount: number diff --git a/src/features/events/__tests__/draft.test.ts b/src/features/events/__tests__/draft.test.ts new file mode 100644 index 000000000..f06508f6e --- /dev/null +++ b/src/features/events/__tests__/draft.test.ts @@ -0,0 +1,239 @@ +import { + areEventDetailsValid, + buildEventExternal, + buildEventRecord, + changeEventTime, + createEventDraft, + EVENT_DESCRIPTION_MAX_GRAPHEMES, + EVENT_NAME_MAX_GRAPHEMES, + type EventDraft, + eventEndsBeforeStart, + eventStartsInPast, + fromLocalInputValue, + isEventDraftPublishable, + toLocalInputValue, +} from '../draft' +import {parseEventRecord} from '../record' + +const NOW = new Date('2027-01-15T11:05:42.123Z') + +function draft(fields: Partial = {}): EventDraft { + return {...createEventDraft(NOW), name: 'Party', ...fields} +} + +describe('event drafts', () => { + it('starts and ends at the current minute', () => { + expect(createEventDraft(NOW)).toMatchObject({ + step: 'details', + startsAt: '2027-01-15T11:05:00.000Z', + endsAt: '2027-01-15T11:05:00.000Z', + }) + }) + + describe('areEventDetailsValid', () => { + it('needs a name that is not blank', () => { + expect(areEventDetailsValid(draft())).toBe(true) + expect(areEventDetailsValid(draft({name: ' '}))).toBe(false) + }) + + it('counts graphemes, not characters, against the name limit', () => { + expect( + areEventDetailsValid( + draft({name: '🎉'.repeat(EVENT_NAME_MAX_GRAPHEMES)}), + ), + ).toBe(true) + expect( + areEventDetailsValid( + draft({name: 'a'.repeat(EVENT_NAME_MAX_GRAPHEMES + 1)}), + ), + ).toBe(false) + }) + + it('limits the description', () => { + expect( + areEventDetailsValid( + draft({ + description: 'a'.repeat(EVENT_DESCRIPTION_MAX_GRAPHEMES + 1), + }), + ), + ).toBe(false) + }) + }) + + it('flags an end before the start, but not an equal one', () => { + expect(eventEndsBeforeStart(draft())).toBe(false) + expect( + eventEndsBeforeStart(draft({endsAt: '2027-01-15T11:04:00.000Z'})), + ).toBe(true) + }) + + it('warns about a past start only beyond the grace window', () => { + const now = NOW.getTime() + expect(eventStartsInPast(draft(), now + 14 * 60e3)).toBe(false) + expect(eventStartsInPast(draft(), now + 16 * 60e3)).toBe(true) + }) + + it('is publishable once finished with valid details and times', () => { + expect(isEventDraftPublishable(draft())).toBe(false) + expect(isEventDraftPublishable(draft({step: 'done'}))).toBe(true) + expect( + isEventDraftPublishable( + draft({step: 'done', endsAt: '2027-01-15T11:00:00.000Z'}), + ), + ).toBe(false) + }) + + describe('changeEventTime', () => { + it('moves the end along when the start passes it', () => { + expect( + changeEventTime(draft(), 'startsAt', '2027-01-16T10:00:00.000Z'), + ).toEqual({ + startsAt: '2027-01-16T10:00:00.000Z', + endsAt: '2027-01-16T10:00:00.000Z', + }) + }) + + it('leaves a later end alone', () => { + const later = draft({endsAt: '2027-01-20T10:00:00.000Z'}) + expect( + changeEventTime(later, 'startsAt', '2027-01-16T10:00:00.000Z'), + ).toEqual({startsAt: '2027-01-16T10:00:00.000Z'}) + }) + + it('lets the end go before the start, for validation to catch', () => { + expect( + changeEventTime(draft(), 'endsAt', '2027-01-14T10:00:00.000Z'), + ).toEqual({endsAt: '2027-01-14T10:00:00.000Z'}) + }) + }) + + it('round-trips local input values', () => { + const iso = '2027-01-15T11:05:00.000Z' + expect(fromLocalInputValue(toLocalInputValue(iso))).toBe(iso) + expect(fromLocalInputValue('')).toBeUndefined() + }) + + describe('buildEventRecord', () => { + const opts = {now: NOW, timeZone: 'America/New_York', country: 'US'} + + it('writes the minimal record', () => { + expect(buildEventRecord(draft({name: ' Party '}), opts)).toEqual({ + $type: 'community.lexicon.calendar.event', + name: 'Party', + createdAt: NOW.toISOString(), + startsAt: '2027-01-15T11:05:00.000Z', + status: 'community.lexicon.calendar.event#scheduled', + timezone: 'America/New_York', + }) + }) + + it('keeps a distinct end and a trimmed description', () => { + const record = buildEventRecord( + draft({ + endsAt: '2027-01-15T14:00:00.000Z', + description: ' Bring snacks ', + }), + opts, + ) + expect(record).toMatchObject({ + endsAt: '2027-01-15T14:00:00.000Z', + description: 'Bring snacks', + }) + }) + + it('makes a link location an online event that our card can join', () => { + const record = buildEventRecord( + draft({location: 'https://twitch.tv/someone'}), + opts, + ) + expect(record).toMatchObject({ + mode: 'community.lexicon.calendar.event#virtual', + locations: [ + { + $type: 'community.lexicon.calendar.event#uri', + uri: 'https://twitch.tv/someone', + }, + ], + }) + expect(parseEventRecord(record)?.joinUrl).toBe( + 'https://twitch.tv/someone', + ) + }) + + it.each(['zoom.us/j/123', 'meet.google.com/abc-defg-hij', 'twitch.tv'])( + 'treats the bare domain %s as an online link', + location => { + expect(buildEventRecord(draft({location}), opts)).toMatchObject({ + mode: 'community.lexicon.calendar.event#virtual', + locations: [{uri: `https://${location}`}], + }) + }, + ) + + it.each(['Prospect Park', 'St. Mark’s Church', 'Room 4.2'])( + 'keeps %s as a place', + location => { + expect(buildEventRecord(draft({location}), opts)).toMatchObject({ + mode: 'community.lexicon.calendar.event#inperson', + }) + }, + ) + + it('makes a place an in-person address our card can show', () => { + const record = buildEventRecord(draft({location: 'Prospect Park'}), opts) + expect(record).toMatchObject({ + mode: 'community.lexicon.calendar.event#inperson', + locations: [ + { + $type: 'community.lexicon.location.address', + name: 'Prospect Park', + country: 'US', + }, + ], + }) + expect(parseEventRecord(record)?.location).toBe('Prospect Park') + }) + + it('stores a cover as the thumbnail media', () => { + const blob = {ref: {$link: 'bafkreicover'}} as never + expect( + buildEventRecord(draft(), { + ...opts, + cover: {blob, width: 1500, height: 500}, + }).media, + ).toEqual([ + { + role: 'thumbnail', + content: blob, + aspect_ratio: {width: 1500, height: 500}, + }, + ]) + }) + + it('keeps a place when the country is unknown', () => { + const record = buildEventRecord(draft({location: 'Prospect Park'}), { + now: NOW, + }) + expect(record).toMatchObject({ + mode: 'community.lexicon.calendar.event#inperson', + locations: [{name: 'Prospect Park', country: 'ZZ'}], + }) + expect(record).not.toHaveProperty('timezone') + expect(parseEventRecord(record)?.location).toBe('Prospect Park') + }) + }) + + it('links the post to the event page by DID', () => { + expect( + buildEventExternal(draft({location: 'The park'}), { + did: 'did:plc:alice', + rkey: '3kevent', + locale: 'en-US', + }), + ).toEqual({ + uri: 'https://blacksky.community/event/did:plc:alice/3kevent', + title: 'Party', + description: expect.stringContaining(' · The park'), + }) + }) +}) diff --git a/src/features/events/components/EventEmbed.tsx b/src/features/events/components/EventEmbed.tsx index f020b89bb..1455e2ca3 100644 --- a/src/features/events/components/EventEmbed.tsx +++ b/src/features/events/components/EventEmbed.tsx @@ -18,7 +18,8 @@ import {Text} from '#/components/Typography' import {eventLinkLabel, eventPhase} from '../format' import {eventPoster} from '../poster' import {useEventQuery} from '../queries' -import {coverUrl, parseEventRecord} from '../record' +import {coverUrl, type ParsedEvent, parseEventRecord} from '../record' +import {type EventView} from '../types' import {eventAtUri, type EventRef, makeEventLink} from '../url' import {EventMeta} from './EventMeta' import {RsvpButtons} from './RsvpButtons' @@ -34,9 +35,6 @@ export function EventEmbed({ onOpen?: () => void style?: StyleProp }) { - const t = useTheme() - const {_, i18n} = useLingui() - const openLink = useOpenLink() const {data: did} = useResolveDidQuery(eventRef.actor) const {data: event} = useEventQuery( did ? eventAtUri(did, eventRef.rkey) : undefined, @@ -50,9 +48,88 @@ export function EventEmbed({ return } + return ( + + ) +} + +export function EventEmbedCard({ + event, + parsed, + rkey, + onOpen, + style, + preview, +}: { + event: EventView + parsed: ParsedEvent + rkey: string + preview?: boolean + onOpen?: () => void + style?: StyleProp +}) { + const t = useTheme() + const {_, i18n} = useLingui() + const openLink = useOpenLink() const phase = eventPhase(parsed, new Date()) const cover = coverUrl(event) const poster = eventPoster(event.uri, parsed) + const content = ( + + {cover ? ( + {_(msg`Cover + ) : ( + + {poster.emoji} + + )} + + {(parsed.cancelled || phase === 'current') && ( + + {parsed.cancelled ? ( + Cancelled + ) : ( + Happening now + )} + + )} + + {parsed.name} + + + + + ) return ( - - - {cover ? ( - {_(msg`Cover - ) : ( - - {poster.emoji} - - )} - - {(parsed.cancelled || phase === 'current') && ( - - {parsed.cancelled ? ( - Cancelled - ) : ( - Happening now - )} - - )} - - {parsed.name} - - - - - + {preview ? ( + content + ) : ( + + {content} + + )} {!parsed.cancelled && phase !== 'past' && ( {parsed.joinUrl && ( @@ -122,13 +156,18 @@ export function EventEmbed({ label={_(msg`Join online at ${toNiceDomain(parsed.joinUrl)}`)} size="small" color={phase === 'current' ? 'primary' : 'secondary'} + disabled={preview} onPress={() => openLink(parsed.joinUrl!, undefined, true)}> Join · {toNiceDomain(parsed.joinUrl)} )} - + )} diff --git a/src/features/events/components/RsvpButtons.tsx b/src/features/events/components/RsvpButtons.tsx index 9377ec3b9..3280e7fd4 100644 --- a/src/features/events/components/RsvpButtons.tsx +++ b/src/features/events/components/RsvpButtons.tsx @@ -22,10 +22,12 @@ export function RsvpButtons({ event, logContext, size = 'small', + disabled, }: { event: EventView logContext: RsvpLogContext size?: 'small' | 'large' + disabled?: boolean }) { const {_} = useLingui() const requireAuth = useRequireAuth() @@ -72,7 +74,7 @@ export function RsvpButtons({ label={selected ? choice.removeLabel : choice.label} size={size} color={selected ? 'primary' : 'secondary'} - disabled={isPending} + disabled={isPending || disabled} style={[a.flex_1, a.px_xs]} onPress={() => onPress(choice.status)}> {selected && } diff --git a/src/features/events/draft.ts b/src/features/events/draft.ts new file mode 100644 index 000000000..8799acb0e --- /dev/null +++ b/src/features/events/draft.ts @@ -0,0 +1,246 @@ +import {type BlobRef} from '@atproto/api' +import {countGraphemes} from 'unicode-segmenter/grapheme' + +import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext' +import {EVENT_COLLECTION} from './types' + +export const EVENT_NAME_MAX_GRAPHEMES = 180 +export const EVENT_DESCRIPTION_MAX_GRAPHEMES = 1000 +// The start defaults to "now", so a short grace keeps the warning from +// appearing while the person is still filling in the card. +const PAST_START_GRACE_MS = 15 * 60e3 + +export type EventDraftStep = 'details' | 'when' | 'cover' | 'done' + +export type EventCover = + | {path: string; mime: string; width: number; height: number} + | {url: string} + +export type EventDraft = { + step: EventDraftStep + name: string + description: string + location: string + startsAt: string + endsAt: string + cover?: EventCover + coverRemoved?: boolean +} + +export type EventDraftFields = Omit + +export function createEventDraft(now = new Date()): EventDraft { + const start = new Date(now) + start.setSeconds(0, 0) + const iso = start.toISOString() + return { + step: 'details', + name: '', + description: '', + location: '', + startsAt: iso, + endsAt: iso, + } +} + +export function areEventDetailsValid(draft: EventDraft): boolean { + const name = draft.name.trim() + return ( + name.length > 0 && + countGraphemes(name) <= EVENT_NAME_MAX_GRAPHEMES && + countGraphemes(draft.description.trim()) <= EVENT_DESCRIPTION_MAX_GRAPHEMES + ) +} + +export function eventEndsBeforeStart(draft: EventDraft): boolean { + return Date.parse(draft.endsAt) < Date.parse(draft.startsAt) +} + +export function eventStartsInPast(draft: EventDraft, now = Date.now()) { + return Date.parse(draft.startsAt) < now - PAST_START_GRACE_MS +} + +export function isEventDraftPublishable(draft: EventDraft): boolean { + return ( + draft.step === 'done' && + areEventDetailsValid(draft) && + !eventEndsBeforeStart(draft) + ) +} + +export type EventTimeField = 'startsAt' | 'endsAt' + +export function changeEventTime( + draft: EventDraft, + field: EventTimeField, + iso: string, +): Partial { + if (field === 'startsAt' && Date.parse(draft.endsAt) < Date.parse(iso)) { + return {startsAt: iso, endsAt: iso} + } + return {[field]: iso} +} + +export function formatEventDraftDate(iso: string, locale: string) { + return new Intl.DateTimeFormat(locale, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(iso)) +} + +const pad = (n: number) => String(n).padStart(2, '0') + +/** For ``, which takes local wall-clock time. */ +export function toLocalInputValue(iso: string): string { + const d = new Date(iso) + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}` +} + +export function fromLocalInputValue(value: string): string | undefined { + const date = new Date(value) + return isNaN(date.getTime()) ? undefined : date.toISOString() +} + +export function deviceTimeZone(): string | undefined { + try { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone + new Intl.DateTimeFormat('en-US', {timeZone: zone}) + return zone + } catch { + return undefined + } +} + +export function eventLocationUrl(draft: EventDraft): string | undefined { + return webUrl(draft.location.trim()) +} + +// The address lexicon requires a country, and ZZ is CLDR's unknown region. +const UNKNOWN_COUNTRY = 'ZZ' +const BARE_DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}(\/\S*)?$/i + +function webUrl(value: string): string | undefined { + if (BARE_DOMAIN.test(value)) value = `https://${value}` + try { + const {protocol} = new URL(value) + return protocol === 'http:' || protocol === 'https:' ? value : undefined + } catch { + return undefined + } +} + +export function buildEventRecord( + draft: EventDraft, + { + now, + timeZone, + country, + cover, + }: { + now: Date + timeZone?: string + country?: string + cover?: {blob: BlobRef; width: number; height: number} + }, +) { + const description = draft.description.trim() + const location = draft.location.trim() + const locationUrl = webUrl(location) + return { + $type: EVENT_COLLECTION, + name: draft.name.trim(), + createdAt: now.toISOString(), + startsAt: draft.startsAt, + ...(draft.endsAt !== draft.startsAt && {endsAt: draft.endsAt}), + status: `${EVENT_COLLECTION}#scheduled`, + ...(description && {description}), + ...(timeZone && {timezone: timeZone}), + ...(cover && { + media: [ + { + role: 'thumbnail', + content: cover.blob, + aspect_ratio: {width: cover.width, height: cover.height}, + }, + ], + }), + ...(locationUrl + ? { + mode: `${EVENT_COLLECTION}#virtual`, + locations: [{$type: `${EVENT_COLLECTION}#uri`, uri: locationUrl}], + } + : location + ? { + mode: `${EVENT_COLLECTION}#inperson`, + locations: [ + { + $type: 'community.lexicon.location.address', + name: location, + country: country || UNKNOWN_COUNTRY, + }, + ], + } + : {}), + } +} + +export function eventPageUrl(did: string, rkey: string) { + return `${DEFAULT_BRAND_CONFIG.web.domains.main}/event/${did}/${rkey}` +} + +export function buildEventExternal( + draft: EventDraft, + {did, rkey, locale}: {did: string; rkey: string; locale: string}, +) { + const location = draft.location.trim() + const when = new Intl.DateTimeFormat(locale, { + weekday: 'short', + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + timeZoneName: 'short', + }).format(new Date(draft.startsAt)) + return { + uri: eventPageUrl(did, rkey), + title: draft.name.trim(), + description: location ? `${when} · ${location}` : when, + } +} + +const STEPS: EventDraftStep[] = ['details', 'when', 'cover', 'done'] + +/** For server drafts, which hold no local files: a picked cover is dropped. */ +export function encodeEventDraft({cover, coverRemoved, ...rest}: EventDraft) { + return { + ...rest, + ...(cover && 'url' in cover && {cover: {url: cover.url}}), + ...(coverRemoved && {coverRemoved}), + } +} + +export function decodeEventDraft(value: unknown): EventDraft | undefined { + if (!value || typeof value !== 'object') return undefined + const v = value as Record + const strings = ['name', 'description', 'location', 'startsAt', 'endsAt'] + if ( + !STEPS.includes(v.step as EventDraftStep) || + !strings.every(k => typeof v[k] === 'string') || + isNaN(Date.parse(v.startsAt as string)) || + isNaN(Date.parse(v.endsAt as string)) + ) { + return undefined + } + const coverUrl = (v.cover as {url?: unknown} | undefined)?.url + return { + step: v.step as EventDraftStep, + name: v.name as string, + description: v.description as string, + location: v.location as string, + startsAt: v.startsAt as string, + endsAt: v.endsAt as string, + ...(typeof coverUrl === 'string' && + webUrl(coverUrl) && {cover: {url: coverUrl}}), + ...(v.coverRemoved === true && {coverRemoved: true}), + } +} diff --git a/src/lib/api/__tests__/event-publish.test.ts b/src/lib/api/__tests__/event-publish.test.ts new file mode 100644 index 000000000..5682262ac --- /dev/null +++ b/src/lib/api/__tests__/event-publish.test.ts @@ -0,0 +1,270 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {logger} from '#/logger' +import {type EventDraft} from '#/features/events/draft' +import {post} from '../index' +import {imageToThumb} from '../resolve' +import {postToSpace} from '../space-post' +import {uploadBlob} from '../upload-blob' + +jest.mock('expo-localization', () => ({ + getLocales: () => [{languageTag: 'en-US', regionCode: 'US'}], +})) +jest.mock('#/state/gallery', () => ({compressImage: jest.fn()})) +jest.mock('#/state/queries/resolve-link', () => ({ + fetchResolveGifQuery: jest.fn(), + fetchResolveLinkQuery: jest.fn(), +})) +jest.mock('#/state/queries/threadgate', () => ({ + createThreadgateRecord: jest.fn(), + threadgateAllowUISettingToAllowRecordValue: jest.fn(() => []), +})) +jest.mock( + '@ipld/dag-cbor', + () => ({encode: (v: unknown) => Buffer.from(JSON.stringify(v))}), + {virtual: true}, +) +jest.mock('multiformats/cid', () => ({ + CID: {createV1: () => ({toString: () => 'bafyreifake'})}, +})) +jest.mock('../space-post', () => ({postToSpace: jest.fn()})) +jest.mock('../resolve', () => ({imageToThumb: jest.fn()})) +jest.mock('../upload-blob', () => ({uploadBlob: jest.fn()})) + +const COVER_BLOB = { + $type: 'blob', + ref: {$link: 'bafkreicover'}, + mimeType: 'image/jpeg', + size: 1234, +} + +const queryClient = {invalidateQueries: jest.fn()} as unknown as QueryClient +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +const event: EventDraft = { + step: 'done', + name: 'Live Turntable Party', + description: 'Theme: songs by Aquarians', + location: 'Prospect Park', + startsAt: '2027-01-15T00:00:00.000Z', + endsAt: '2027-01-15T03:00:00.000Z', +} + +type Write = { + collection: string + rkey: string + value: Record & { + embed?: {$type: string; external: Record} + } +} + +function setup() { + const applyWrites = jest.fn((_input: {writes: Write[]; validate?: boolean}) => + Promise.resolve({}), + ) + const agent = { + assertDid: 'did:plc:alice', + com: {atproto: {repo: {applyWrites}}}, + } as unknown as AtpAgent + return {agent, applyWrites} +} + +function thread(embed: Record, extra = {}) { + return { + posts: [ + { + id: 'post-1', + richtext: {text: 'Come through', facets: []}, + shortenedGraphemeLength: 12, + labels: [], + embed, + }, + ], + postgate: {}, + threadgate: [], + blackskyOnly: false, + ...extra, + } as never +} + +describe('publishing a post with an event', () => { + it('writes the event and the post together, linking the post to it', async () => { + const {agent, applyWrites} = setup() + + const result = await post(agent, queryClient, {thread: thread({event})}) + + expect(applyWrites).toHaveBeenCalledTimes(1) + const [{writes, validate}] = applyWrites.mock.calls[0] + expect(validate).toBeUndefined() + expect(writes.map(w => w.collection)).toEqual([ + 'community.lexicon.calendar.event', + 'app.bsky.feed.post', + ]) + const [eventWrite, postWrite] = writes + expect(eventWrite.value).toMatchObject({ + $type: 'community.lexicon.calendar.event', + name: 'Live Turntable Party', + startsAt: event.startsAt, + endsAt: event.endsAt, + mode: 'community.lexicon.calendar.event#inperson', + locations: [ + { + $type: 'community.lexicon.location.address', + name: 'Prospect Park', + country: 'US', + }, + ], + }) + expect(postWrite.value.embed).toEqual({ + $type: 'app.bsky.embed.external', + external: expect.objectContaining({ + uri: `https://blacksky.community/event/did:plc:alice/${eventWrite.rkey}`, + title: 'Live Turntable Party', + }), + }) + expect(result.event).toEqual({ + uri: `at://did:plc:alice/community.lexicon.calendar.event/${eventWrite.rkey}`, + }) + }) + + it('still asks the PDS to validate posts without an event', async () => { + const {agent, applyWrites} = setup() + + const result = await post(agent, queryClient, {thread: thread({})}) + + expect(applyWrites.mock.calls[0][0].validate).toBe(true) + expect(result).not.toHaveProperty('event') + }) + + it('refuses an event on a Blacksky-only post', async () => { + const {agent, applyWrites} = setup() + + await expect( + post(agent, queryClient, { + thread: thread({event}, {blackskyOnly: true}), + }), + ).rejects.toThrow('Events are only available on public posts.') + expect(applyWrites).not.toHaveBeenCalled() + }) + + it('refuses an event in a private space', async () => { + const {agent} = setup() + + await expect( + post(agent, queryClient, { + thread: thread({event}, {communitySpaceUri: SPACE}), + }), + ).rejects.toThrow('Events are only available on public posts.') + expect(jest.mocked(postToSpace)).not.toHaveBeenCalled() + }) + + describe('with a cover image', () => { + let warn: jest.SpyInstance + beforeEach(() => { + jest.mocked(uploadBlob).mockReset() + jest.mocked(imageToThumb).mockReset() + jest + .mocked(uploadBlob) + .mockResolvedValue({data: {blob: COVER_BLOB}} as never) + warn = jest.spyOn(logger, 'warn').mockImplementation(() => {}) + }) + afterEach(() => warn.mockRestore()) + + async function publish(cover: EventDraft['cover']) { + const {agent, applyWrites} = setup() + await post(agent, queryClient, { + thread: thread({event: {...event, cover}}), + }) + const [eventWrite, postWrite] = applyWrites.mock.calls[0][0].writes + return {eventWrite, postWrite} + } + + it('uploads a picked photo once and uses it for the event and the link card', async () => { + const {eventWrite, postWrite} = await publish({ + path: 'file:///cover.jpg', + mime: 'image/jpeg', + width: 1500, + height: 500, + }) + + expect(uploadBlob).toHaveBeenCalledTimes(1) + expect(uploadBlob).toHaveBeenCalledWith( + expect.anything(), + 'file:///cover.jpg', + 'image/jpeg', + ) + expect(eventWrite.value.media).toEqual([ + { + role: 'thumbnail', + content: COVER_BLOB, + aspect_ratio: {width: 1500, height: 500}, + }, + ]) + expect(postWrite.value.embed?.external.thumb).toBe(COVER_BLOB) + }) + + it("downloads a link's image before uploading it", async () => { + jest.mocked(imageToThumb).mockResolvedValue({ + source: { + id: 'x', + path: 'file:///link.jpg', + mime: 'image/jpeg', + width: 1200, + height: 630, + }, + } as never) + + const {eventWrite} = await publish({url: 'https://example.com/og.jpg'}) + + expect(imageToThumb).toHaveBeenCalledWith('https://example.com/og.jpg') + expect(uploadBlob).toHaveBeenCalledWith( + expect.anything(), + 'file:///link.jpg', + 'image/jpeg', + ) + expect(eventWrite.value.media).toEqual([ + expect.objectContaining({aspect_ratio: {width: 1200, height: 630}}), + ]) + }) + + it('stops the post with an error when the upload fails', async () => { + jest.mocked(uploadBlob).mockRejectedValue(new Error('offline')) + const {agent, applyWrites} = setup() + + await expect( + post(agent, queryClient, { + thread: thread({ + event: { + ...event, + cover: { + path: 'file:///cover.jpg', + mime: 'image/jpeg', + width: 1500, + height: 500, + }, + }, + }), + }), + ).rejects.toThrow("Couldn't upload the event image.") + expect(applyWrites).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledWith('Failed to upload the event image', { + safeMessage: 'offline', + }) + }) + + it('stops the post when a link image cannot be read', async () => { + jest.mocked(imageToThumb).mockResolvedValue(undefined) + const {agent, applyWrites} = setup() + + await expect( + post(agent, queryClient, { + thread: thread({ + event: {...event, cover: {url: 'https://x.test/a.jpg'}}, + }), + }), + ).rejects.toThrow("Couldn't upload the event image.") + expect(applyWrites).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index cb63fef81..a54f12498 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -1,3 +1,4 @@ +import {getLocales} from 'expo-localization' import { type $Typed, type AppBskyEmbedExternal, @@ -65,6 +66,14 @@ import { type PostDraft, type ThreadDraft, } from '#/view/com/composer/state/composer' +import { + buildEventExternal, + buildEventRecord, + deviceTimeZone, + type EventCover, +} from '#/features/events/draft' +import {EVENT_COLLECTION} from '#/features/events/types' +import {eventAtUri} from '#/features/events/url' import * as bsky from '#/types/bsky' import {createGIFDescription} from '../gif-alt-text' import {uploadBlob} from './upload-blob' @@ -99,6 +108,12 @@ function refusePoll(thread: ThreadDraft) { } } +function refuseEvent(thread: ThreadDraft) { + if (thread.posts.some(p => p.embed.event)) { + throw new Error(t`Events are only available on public posts.`) + } +} + function refusePollWithAttachments(draft: PostDraft) { if ( draft.embed.poll && @@ -132,6 +147,7 @@ export interface PostOpts { export type PostResult = { uris: string[] + event?: {uri: string} assembly?: { conversationId: string statementCount: number @@ -160,6 +176,7 @@ export async function post( ) } refusePoll(thread) + refuseEvent(thread) return postToSpace(agent, queryClient, space, opts) } @@ -184,6 +201,7 @@ export async function post( const config = thread.communityFeed?.config if (isSpaceBackedFeed(config)) { refusePoll(thread) + refuseEvent(thread) return postToSpace(agent, queryClient, config.space, opts) } @@ -217,6 +235,7 @@ export async function post( isQuoteOfCommunityPost ) { refusePoll(thread) + refuseEvent(thread) return postCommunity(agent, queryClient, opts) } @@ -236,6 +255,9 @@ export async function post( } const pollPost = findPollPost(thread) + const eventPost = thread.posts.find(p => p.embed.event) + const eventRkey = eventPost ? TID.nextStr() : undefined + const locale = getLocales()[0] let replyPromise: | Promise @@ -281,6 +303,14 @@ export async function post( langs = opts.langs.slice(0, 3) } + const eventCover = eventPost?.embed.event?.cover + ? await uploadEventCover( + agent, + eventPost.embed.event.cover, + opts.onStateChange, + ) + : undefined + const did = agent.assertDid const writes: $Typed[] = [] const uris: string[] = [] @@ -294,12 +324,20 @@ export async function post( // Not awaited to avoid waterfalls. const rtPromise = resolveRT(agent, draft.richtext) - const embedPromise = resolveEmbed( - agent, - queryClient, - draft, - opts.onStateChange, - ) + const embedPromise = + draft === eventPost && eventRkey + ? Promise.resolve({ + $type: 'app.bsky.embed.external' as const, + external: { + ...buildEventExternal(draft.embed.event!, { + did, + rkey: eventRkey, + locale: locale?.languageTag ?? 'en-US', + }), + ...(eventCover && {thumb: eventCover.blob}), + }, + }) + : resolveEmbed(agent, queryClient, draft, opts.onStateChange) let labels: $Typed | undefined if (draft.labels.length) { labels = { @@ -382,11 +420,28 @@ export async function post( } } + if (eventPost?.embed.event && eventRkey) { + writes.unshift({ + $type: 'com.atproto.repo.applyWrites#create', + collection: EVENT_COLLECTION, + rkey: eventRkey, + value: buildEventRecord(eventPost.embed.event, { + now: new Date(), + timeZone: deviceTimeZone(), + country: locale?.regionCode ?? undefined, + cover: eventCover, + }), + }) + } + try { await agent.com.atproto.repo.applyWrites({ repo: agent.assertDid, writes: writes, - validate: true, + // A PDS refuses lexicons it does not know when asked to validate, and + // most do not know the event lexicon. Left unset, known ones such as + // the post are still validated. + validate: eventPost ? undefined : true, }) } catch (err) { const e = err as Error @@ -410,7 +465,11 @@ export async function post( ) } - return {uris, assembly} + return { + uris, + assembly, + ...(eventRkey && {event: {uri: eventAtUri(did, eventRkey)}}), + } } async function postCommunity( @@ -870,6 +929,28 @@ async function resolveAssembly( } } +async function uploadEventCover( + agent: AtpAgent, + cover: EventCover, + onStateChange: ((state: string) => void) | undefined, +): Promise<{blob: BlobRef; width: number; height: number}> { + try { + const image = + 'url' in cover ? (await imageToThumb(cover.url))?.source : cover + if (!image) throw new Error('The image could not be read') + onStateChange?.(t`Uploading event image...`) + const response = await uploadBlob(agent, image.path, image.mime) + return {blob: response.data.blob, width: image.width, height: image.height} + } catch (e) { + logger.warn(`Failed to upload the event image`, { + safeMessage: e instanceof Error ? e.message : String(e), + }) + throw new Error( + t`Couldn't upload the event image. Try again, or remove the image.`, + ) + } +} + async function uploadAssemblyThumb( agent: AtpAgent, conversationId: string, diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index c71baa796..951fc8793 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -126,6 +126,8 @@ import {type ComposerOpts, type OnPostSuccessData} from '#/state/shell/composer' import {CharProgress} from '#/view/com/composer/char-progress/CharProgress' import {ComposerReplyTo} from '#/view/com/composer/ComposerReplyTo' import {DraftsButton} from '#/view/com/composer/drafts/DraftsButton' +import {EventEditor} from '#/view/com/composer/event/EventEditor' +import {SelectEventBtn} from '#/view/com/composer/event/SelectEventBtn' import { ExternalEmbedGif, ExternalEmbedLink, @@ -197,6 +199,8 @@ import { composerReducer, createComposerState, type EmbedDraft, + isEventAllowed, + isEventPostable, isPollAllowed, isPollPostable, MAX_GALLERY_IMAGES, @@ -204,6 +208,7 @@ import { type PostDraft, postHasAttachment, type ThreadDraft, + threadHasEvent, threadHasPoll, } from './state/composer' import { @@ -818,7 +823,8 @@ export const ComposePost = ({ post.richtext.text.trim().length > 0 || post.embed.media || post.embed.link || - post.embed.poll, + post.embed.poll || + post.embed.event, ) ax.metric('draft:discard', { logContext: 'ComposerClose', @@ -843,6 +849,7 @@ export const ComposePost = ({ // Has link if (firstPost.embed.link) return false if (firstPost.embed.poll) return false + if (firstPost.embed.event) return false return true }, [thread.posts]) @@ -882,7 +889,8 @@ export const ComposePost = ({ post.shortenedGraphemeLength > 0 || post.embed.media || post.embed.link || - post.embed.poll, + post.embed.poll || + post.embed.event, ) // Show discard prompt if there's content AND either: @@ -973,6 +981,8 @@ export const ComposePost = ({ const canAddPoll = isPollAllowed(thread, replyTo?.uri) && !threadHasPoll(thread) + const canAddEvent = + isEventAllowed(thread, replyTo?.uri) && !threadHasEvent(thread) const getAssemblyErrorMessage = useCallback( (code: AssemblyErrorCode): string => { @@ -1010,7 +1020,8 @@ export const ComposePost = ({ post.embed.media?.type === 'video' && post.embed.media.video.status === 'error' ) && - isPollPostable(post)), + isPollPostable(post) && + isEventPostable(post)), ) const getFilteredThread = useCallback((): { @@ -1101,6 +1112,15 @@ export const ComposePost = ({ isReplay: result.assembly.isReplay, }) } + const event = filteredThread.posts.find(p => p.embed.event)?.embed.event + if (result.event && event) { + ax.metric('event:create', { + uri: result.event.uri, + hasDescription: event.description.trim().length > 0, + hasLocation: event.location.trim().length > 0, + hasCover: !!event.cover, + }) + } /* * Wait for app view to have received the post(s). If this fails, it's @@ -1457,6 +1477,7 @@ export const ComposePost = ({ post={activePost} dispatch={dispatch} canAddPoll={canAddPoll} + canAddEvent={canAddEvent} showAddButton={ !isEmptyPost(activePost) && (!nextPost || !isEmptyPost(nextPost)) } @@ -1713,11 +1734,17 @@ let ComposerPost = memo(function ComposerPost({ ) const hasPoll = !!post.embed.poll + const hasEvent = !!post.embed.event const onPhotoPasted = useCallback( async (uri: string) => { - if (hasPoll) { + if (hasPoll || hasEvent) { if (IS_WEB) { - Toast.show(l`Remove the discussion to add media`, {type: 'warning'}) + Toast.show( + hasPoll + ? l`Remove the discussion to add media` + : l`Remove the event to add media`, + {type: 'warning'}, + ) } return } @@ -1743,7 +1770,7 @@ let ComposerPost = memo(function ComposerPost({ onImageAdd([res]) } }, - [post.id, hasPoll, onSelectVideo, onImageAdd, l], + [post.id, hasPoll, hasEvent, onSelectVideo, onImageAdd, l], ) useHideKeyboardOnBackground() @@ -2040,6 +2067,8 @@ function ComposerEmbeds({ )} + {embed.event && } + {!embed.media && embed.link && ( void canAddPoll: boolean + canAddEvent: boolean showAddButton: boolean onError: (error: string) => void onSelectVideo: (postId: string, asset: ImagePickerAsset) => void @@ -2236,7 +2267,8 @@ function ComposerFooter({ const {gtPhone} = useBreakpoints() const ax = useAnalytics() const arePollsEnabled = IS_DEV || ax.features.enabled(ax.features.PollsEnable) - const hasPoll = !!post.embed.poll + const areEventsEnabled = ax.features.enabled(ax.features.EventsEnable) + const hasExclusiveEmbed = !!post.embed.poll || !!post.embed.event /* * Once we've allowed a certain type of asset to be selected, we don't allow * other types of media to be selected. @@ -2264,7 +2296,7 @@ function ComposerFooter({ } else { isMediaSelectionDisabled = !!media } - if (hasPoll) { + if (hasExclusiveEmbed) { isMediaSelectionDisabled = true } @@ -2352,7 +2384,7 @@ function ComposerFooter({ /> {arePollsEnabled && ( )} + {areEventsEnabled && ( + dispatch({type: 'embed_add_event'})} + disabled={!canAddEvent || postHasAttachment(post)} + /> + )} {IS_WEB && gtPhone ? ( diff --git a/src/view/com/composer/drafts/DraftItem.tsx b/src/view/com/composer/drafts/DraftItem.tsx index 539088f9d..48a80954e 100644 --- a/src/view/com/composer/drafts/DraftItem.tsx +++ b/src/view/com/composer/drafts/DraftItem.tsx @@ -9,6 +9,7 @@ import {logger} from '#/view/com/composer/drafts/state/logger' import {TimeElapsed} from '#/view/com/util/TimeElapsed' import {atoms as a, select, useTheme} from '#/alf' import {Button} from '#/components/Button' +import {CalendarDays_Stroke2_Corner0_Rounded as CalendarIcon} from '#/components/icons/CalendarDays' import {CirclePlus_Stroke2_Corner0_Rounded as CirclePlusIcon} from '#/components/icons/CirclePlus' import {type Props as SVGIconProps} from '#/components/icons/common' import {DotGrid3x1_Stroke2_Corner0_Rounded as DotsIcon} from '#/components/icons/DotGrid' @@ -20,6 +21,7 @@ import * as Prompt from '#/components/Prompt' import {RichText} from '#/components/RichText' import {Text} from '#/components/Typography' import {IS_WEB} from '#/env' +import {type EventDraft, formatEventDraftDate} from '#/features/events/draft' import {type DraftPostDisplay, type DraftSummary} from './state/schema' import * as storage from './state/storage' @@ -110,6 +112,8 @@ export function DraftItem({ {post.poll && } + {post.event && } + {hasMetadata && ( {mediaExistsOnOtherDevice && ( @@ -389,3 +393,42 @@ function DraftMediaPreview({post}: {post: DraftPostDisplay}) { ) } + +function DraftEventPreview({event}: {event: EventDraft}) { + const t = useTheme() + const {_, i18n} = useLingui() + return ( + + + + + {_( + msg({ + message: 'Event', + comment: + 'Label on a draft preview showing the draft has an event', + }), + )} + + + {event.name.trim().length > 0 && ( + + {event.name.trim()} + + )} + + {formatEventDraftDate(event.startsAt, i18n.locale)} + + + ) +} diff --git a/src/view/com/composer/drafts/state/__tests__/api-event.test.ts b/src/view/com/composer/drafts/state/__tests__/api-event.test.ts new file mode 100644 index 000000000..bce6334e0 --- /dev/null +++ b/src/view/com/composer/drafts/state/__tests__/api-event.test.ts @@ -0,0 +1,189 @@ +import {type AppBskyDraftDefs, RichText} from '@atproto/api' + +import { + type ComposerState, + type PostDraft, +} from '#/view/com/composer/state/composer' +import {type EventDraft} from '#/features/events/draft' +import { + composerStateToDraft, + draftToComposerPosts, + draftViewToSummary, +} from '../api' + +jest.mock('../storage', () => ({ + mediaExists: jest.fn(() => true), + loadMediaFromLocal: jest.fn(), + saveMediaToLocal: jest.fn(), +})) +jest.mock('../logger', () => ({ + logger: { + debug: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + info: jest.fn(), + }, +})) +jest.mock('#/lib/media/manip', () => ({getImageDim: jest.fn()})) +jest.mock('#/lib/media/video/util', () => ({mimeToExt: jest.fn(() => 'mp4')})) +jest.mock('#/lib/deviceName', () => ({getDeviceName: () => 'Test device'})) +jest.mock('#/analytics/identifiers', () => ({getDeviceId: () => 'device-1'})) +jest.mock('#/state/session/agent', () => ({createPublicAgent: jest.fn()})) +jest.mock('#/lib/api/resolve', () => ({resolveLink: jest.fn()})) +jest.mock('#/state/queries/threadgate/util', () => ({ + threadgateAllowUISettingToAllowRecordValue: jest.fn(() => undefined), +})) +jest.mock('#/state/gallery', () => ({})) +jest.mock('#/view/com/composer/state/composer', () => ({ + LEGACY_IMAGES_EMBED_MAX: 4, +})) + +const EVENT_KEY = 'communityBlackskyEvent' + +const event: EventDraft = { + step: 'when', + name: 'Party', + description: 'Bring snacks', + location: 'Prospect Park', + startsAt: '2027-01-15T00:00:00.000Z', + endsAt: '2027-01-15T03:00:00.000Z', +} + +function savedEvent(draft: AppBskyDraftDefs.Draft, index = 0): unknown { + return (draft.posts[index] as unknown as Record)[EVENT_KEY] +} + +function asStored(draft: AppBskyDraftDefs.Draft): AppBskyDraftDefs.Draft { + return JSON.parse(JSON.stringify(draft)) as AppBskyDraftDefs.Draft +} + +function post(embed: Partial, text = ''): PostDraft { + return { + id: 'p', + richtext: new RichText({text}), + shortenedGraphemeLength: text.length, + labels: [], + embed: {quote: undefined, link: undefined, media: undefined, ...embed}, + } +} + +function state(posts: PostDraft[]): ComposerState { + return { + activePostIndex: 0, + mutableNeedsFocusActive: false, + isDirty: true, + thread: { + posts, + postgate: {} as never, + threadgate: [], + blackskyOnly: false, + }, + } +} + +function draftPost(extra: Record): AppBskyDraftDefs.DraftPost { + return { + $type: 'app.bsky.draft.defs#draftPost', + text: 'hello', + ...extra, + } +} + +function draftOf(posts: AppBskyDraftDefs.DraftPost[]): AppBskyDraftDefs.Draft { + return {$type: 'app.bsky.draft.defs#draft', posts} +} + +describe('draft events', () => { + it('saves the event as an extra property on the draft post', async () => { + const {draft} = await composerStateToDraft(state([post({event})])) + expect(savedEvent(draft)).toStrictEqual(event) + }) + + it('omits the property when there is no event', async () => { + const {draft} = await composerStateToDraft(state([post({}, 'text')])) + expect(EVENT_KEY in draft.posts[0]).toBe(false) + }) + + it("keeps a link's image but drops a picked photo, which lives only on this device", async () => { + const withLink = await composerStateToDraft( + state([post({event: {...event, cover: {url: 'https://x.test/og.jpg'}}})]), + ) + expect(savedEvent(withLink.draft)).toMatchObject({ + cover: {url: 'https://x.test/og.jpg'}, + }) + + const withPhoto = await composerStateToDraft( + state([ + post({ + event: { + ...event, + cover: { + path: 'file:///a.jpg', + mime: 'image/jpeg', + width: 3, + height: 1, + }, + }, + }), + ]), + ) + expect(savedEvent(withPhoto.draft)).not.toHaveProperty('cover') + }) + + it('round-trips an event through save and restore', async () => { + const {draft} = await composerStateToDraft( + state([post({event: {...event, coverRemoved: true}}, 'come')]), + ) + const {posts} = await draftToComposerPosts(asStored(draft), new Map()) + expect(posts[0].embed.event).toEqual({...event, coverRemoved: true}) + expect(posts[0].richtext.text).toBe('come') + }) + + it.each([ + {kind: 'a missing name', value: {...event, name: undefined}}, + {kind: 'an unknown step', value: {...event, step: 'launch'}}, + {kind: 'an unreadable date', value: {...event, startsAt: 'soon'}}, + {kind: 'a non-object', value: 'party'}, + ])('ignores a saved event with $kind', async ({value}) => { + const {posts} = await draftToComposerPosts( + draftOf([draftPost({[EVENT_KEY]: value})]), + new Map(), + ) + expect(posts[0].embed.event).toBeUndefined() + }) + + it('does not restore an event beside a quote', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({ + [EVENT_KEY]: event, + embedRecords: [ + { + $type: 'app.bsky.draft.defs#draftEmbedRecord', + record: { + uri: 'at://did:plc:a/app.bsky.feed.post/1', + cid: 'bafyreiquote', + }, + }, + ], + }), + ]), + new Map(), + ) + expect(posts[0].embed.quote).toBeDefined() + expect(posts[0].embed.event).toBeUndefined() + }) + + it('shows the event in the draft list', () => { + const summary = draftViewToSummary({ + view: { + id: 'd1', + draft: draftOf([draftPost({[EVENT_KEY]: event})]), + createdAt: '2027-01-01T00:00:00.000Z', + updatedAt: '2027-01-01T00:00:00.000Z', + }, + analytics: {logger: {warn: jest.fn()}} as never, + }) + expect(summary.posts[0].event).toEqual(event) + }) +}) diff --git a/src/view/com/composer/drafts/state/api.ts b/src/view/com/composer/drafts/state/api.ts index db7de62ee..278a987f4 100644 --- a/src/view/com/composer/drafts/state/api.ts +++ b/src/view/com/composer/drafts/state/api.ts @@ -23,23 +23,30 @@ import { import {type VideoState} from '#/view/com/composer/state/video' import {type AnalyticsContextType} from '#/analytics' import {getDeviceId} from '#/analytics/identifiers' +import {decodeEventDraft, encodeEventDraft} from '#/features/events/draft' import {type Gif} from '#/features/gifPicker/types' import {logger} from './logger' import {type DraftPostDisplay, type DraftSummary} from './schema' import * as storage from './storage' const DRAFT_POLL_KEY = 'communityBlackskyPoll' +const DRAFT_EVENT_KEY = 'communityBlackskyEvent' // app.bsky.draft.defs is not ours to extend, so the poll travels as an extra // property that the draft schema passes through untouched. type DraftPostWithPoll = AppBskyDraftDefs.DraftPost & { [DRAFT_POLL_KEY]?: unknown + [DRAFT_EVENT_KEY]?: unknown } function readDraftPoll(post: DraftPostWithPoll) { return decodePollDraft(post[DRAFT_POLL_KEY]) } +function readDraftEvent(post: DraftPostWithPoll) { + return decodeEventDraft(post[DRAFT_EVENT_KEY]) +} + const TENOR_HOSTNAME = 'media.tenor.com' const KLIPY_HOSTNAME = 'static.klipy.com' @@ -156,6 +163,12 @@ async function postDraftToServerPost( : {statements} } + if (post.embed.event) { + ;(draftPost as DraftPostWithPoll)[DRAFT_EVENT_KEY] = encodeEventDraft( + post.embed.event, + ) + } + // Add quote record embed if (post.embed.quote) { const resolved = await resolveLink( @@ -454,6 +467,7 @@ export function draftViewToSummary({ video: videos[0], // Only one video per post gif, poll: readDraftPoll(post), + event: readDraftEvent(post), } }) @@ -657,6 +671,17 @@ export async function draftToComposerPosts( ) { embed.poll = poll } + const event = readDraftEvent(post) + if ( + event && + !embed.poll && + !embed.media && + !embed.link && + !embed.quote && + !restoredVideos.has(index) + ) { + embed.event = event + } // Parse labels const labels: string[] = [] diff --git a/src/view/com/composer/drafts/state/schema.ts b/src/view/com/composer/drafts/state/schema.ts index d80339249..9d90504b1 100644 --- a/src/view/com/composer/drafts/state/schema.ts +++ b/src/view/com/composer/drafts/state/schema.ts @@ -5,6 +5,7 @@ import {type AppBskyDraftDefs} from '@atproto/api' import {type PollDraft} from '#/lib/api/poll' +import {type EventDraft} from '#/features/events/draft' /** * Reference to locally cached media file for display @@ -46,6 +47,7 @@ export type DraftPostDisplay = { /** GIF data (from URL) */ gif?: GifDisplay poll?: PollDraft + event?: EventDraft } /** diff --git a/src/view/com/composer/event/EventCoverPicker.tsx b/src/view/com/composer/event/EventCoverPicker.tsx new file mode 100644 index 000000000..ded630ff5 --- /dev/null +++ b/src/view/com/composer/event/EventCoverPicker.tsx @@ -0,0 +1,204 @@ +import {useState} from 'react' +import {Pressable, View} from 'react-native' +import {Image} from 'expo-image' +import {Trans, useLingui} from '@lingui/react/macro' + +import {IMAGE_SIZE_CONFIG_2K_1MB} from '#/lib/constants' +import { + useCameraPermission, + usePhotoLibraryPermission, +} from '#/lib/hooks/usePermissions' +import {compressIfNeeded} from '#/lib/media/manip' +import {openCamera, openCropper, openPicker} from '#/lib/media/picker' +import {type PickerImage} from '#/lib/media/picker.shared' +import {isCancelledError} from '#/lib/strings/errors' +import {logger} from '#/logger' +import { + type ComposerImage, + compressImage, + createComposerImage, +} from '#/state/gallery' +import {EditImageDialog} from '#/view/com/composer/photos/EditImageDialog' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import {useDialogControl} from '#/components/Dialog' +import {useSheetWrapper} from '#/components/Dialog/sheet-wrapper' +import {Camera_Stroke2_Corner0_Rounded as CameraIcon} from '#/components/icons/Camera' +import {StreamingLive_Stroke2_Corner0_Rounded as LibraryIcon} from '#/components/icons/StreamingLive' +import {Trash_Stroke2_Corner0_Rounded as TrashIcon} from '#/components/icons/Trash' +import * as Menu from '#/components/Menu' +import {IS_NATIVE, IS_WEB} from '#/env' + +const ASPECT = 2 + +export function EventCoverPicker({ + cover, + onChange, +}: { + cover?: string + onChange: (image: PickerImage | null) => void +}) { + const t = useTheme() + const {t: l} = useLingui() + const {requestCameraAccessIfNeeded} = useCameraPermission() + const {requestPhotoAccessIfNeeded} = usePhotoLibraryPermission() + const sheetWrapper = useSheetWrapper() + const editControl = useDialogControl() + const [rawImage, setRawImage] = useState() + + const onCamera = async () => { + if (!(await requestCameraAccessIfNeeded())) return + try { + onChange( + await compressIfNeeded( + await openCamera({aspect: [ASPECT, 1]}), + IMAGE_SIZE_CONFIG_2K_1MB, + ), + ) + } catch (e) { + if (!isCancelledError(e)) { + logger.warn('Failed to take event cover photo', {error: e}) + } + } + } + + const onLibrary = async () => { + if (!(await requestPhotoAccessIfNeeded())) return + const items = await sheetWrapper(openPicker()) + if (!items[0]) return + try { + if (IS_NATIVE) { + onChange( + await compressIfNeeded( + await openCropper({imageUri: items[0].path, aspectRatio: ASPECT}), + IMAGE_SIZE_CONFIG_2K_1MB, + ), + ) + } else { + setRawImage(await createComposerImage(items[0])) + editControl.open() + } + } catch (e) { + if (!isCancelledError(e)) { + logger.error('Failed to pick event cover', {error: e}) + } + } + } + + const field = ( + + {cover && ( + + )} + + + + + ) + + return ( + <> + {IS_WEB ? ( + + void onLibrary()}> + {field} + + {cover && ( + + )} + + ) : ( + + + {({props}) => ( + + {field} + + )} + + + + void onCamera()}> + + Upload from Camera + + + + void onLibrary()}> + + Upload from Library + + + + + {cover && ( + <> + + + onChange(null)}> + + Remove image + + + + + + )} + + + )} + + void compressImage(image, IMAGE_SIZE_CONFIG_2K_1MB).then(onChange) + } + aspectRatio={ASPECT} + preselectCrop + /> + + ) +} diff --git a/src/view/com/composer/event/EventDateRange.tsx b/src/view/com/composer/event/EventDateRange.tsx new file mode 100644 index 000000000..9c36a3399 --- /dev/null +++ b/src/view/com/composer/event/EventDateRange.tsx @@ -0,0 +1,139 @@ +import {useState} from 'react' +import {Keyboard, Pressable, View} from 'react-native' +import DatePicker from 'react-native-date-picker' +import {Trans, useLingui} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import {Text} from '#/components/Typography' +import {type EventTimeField} from '#/features/events/draft' +import {type EventDateRangeProps} from './EventDateRange.types' +import {DateBox, FieldLabelText} from './EventFields' + +const FIELDS = ['startsAt', 'endsAt'] as const + +export function EventDateRange({ + startsAt, + endsAt, + isEndInvalid, + onChange, +}: EventDateRangeProps) { + const t = useTheme() + const {t: l, i18n} = useLingui() + const control = Dialog.useDialogControl() + const [field, setField] = useState('startsAt') + const values = {startsAt, endsAt} + const labels = {startsAt: l`Start date`, endsAt: l`End date`} + const short = (iso: string) => + i18n.date(new Date(iso), { + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + }) + + const open = (next: EventTimeField) => { + Keyboard.dismiss() + setField(next) + control.open() + } + + return ( + <> + + {FIELDS.map(key => ( + + {labels[key]} + open(key)}> + + + + ))} + + + + + + + {FIELDS.map(key => { + const active = field === key + return ( + setField(key)} + style={[a.flex_1, a.align_center, a.pt_md]}> + + {key === 'startsAt' ? ( + Start: {short(startsAt)} + ) : ( + End: {short(endsAt)} + )} + + + + ) + })} + + + onChange(field, date.toISOString())} + aria-label={labels[field]} + accessibilityLabel={labels[field]} + accessibilityHint={l`Choose the date and time`} + /> + + + + + + + ) +} diff --git a/src/view/com/composer/event/EventDateRange.types.ts b/src/view/com/composer/event/EventDateRange.types.ts new file mode 100644 index 000000000..6c27096e4 --- /dev/null +++ b/src/view/com/composer/event/EventDateRange.types.ts @@ -0,0 +1,8 @@ +import {type EventTimeField} from '#/features/events/draft' + +export type EventDateRangeProps = { + startsAt: string + endsAt: string + isEndInvalid: boolean + onChange: (field: EventTimeField, iso: string) => void +} diff --git a/src/view/com/composer/event/EventDateRange.web.tsx b/src/view/com/composer/event/EventDateRange.web.tsx new file mode 100644 index 000000000..84db3f539 --- /dev/null +++ b/src/view/com/composer/event/EventDateRange.web.tsx @@ -0,0 +1,112 @@ +import {type CSSProperties, useRef, useState} from 'react' +import {Pressable, View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import { + type EventTimeField, + fromLocalInputValue, + toLocalInputValue, +} from '#/features/events/draft' +import {type EventDateRangeProps} from './EventDateRange.types' +import {DateBox, FieldLabelText} from './EventFields' + +const FIELDS = ['startsAt', 'endsAt'] as const + +const HIDDEN_INPUT: CSSProperties = { + position: 'absolute', + left: 0, + bottom: 0, + width: '100%', + height: 0, + opacity: 0, + border: 0, + padding: 0, + pointerEvents: 'none', +} + +export function EventDateRange({ + startsAt, + endsAt, + isEndInvalid, + onChange, +}: EventDateRangeProps) { + const t = useTheme() + const {t: l} = useLingui() + const inputs = useRef>({}) + const [isPickerUnavailable, setIsPickerUnavailable] = useState( + () => !('showPicker' in HTMLInputElement.prototype), + ) + const values = {startsAt, endsAt} + const labels = {startsAt: l`Start date`, endsAt: l`End date`} + + const renderInput = ( + key: EventTimeField, + style: CSSProperties, + hidden: boolean, + ) => ( + { + inputs.current[key] = el + }} + type="datetime-local" + data-testid={`${key}Input`} + aria-label={labels[key]} + tabIndex={hidden ? -1 : undefined} + value={toLocalInputValue(values[key])} + onChange={e => { + const iso = fromLocalInputValue(e.target.value) + if (iso) onChange(key, iso) + }} + style={style} + /> + ) + + return ( + + {FIELDS.map(key => { + const isInvalid = key === 'endsAt' && isEndInvalid + return ( + + {labels[key]} + {isPickerUnavailable ? ( + renderInput( + key, + { + boxSizing: 'border-box', + width: '100%', + padding: '6px 16px', + borderRadius: 10, + border: `1px solid ${ + isInvalid ? t.palette.negative_500 : 'transparent' + }`, + background: t.atoms.bg_contrast_50.backgroundColor, + color: t.atoms.text.color, + colorScheme: t.scheme, + font: 'inherit', + fontSize: a.text_lg.fontSize, + }, + false, + ) + ) : ( + { + try { + inputs.current[key]?.showPicker() + } catch { + setIsPickerUnavailable(true) + } + }}> + + {renderInput(key, HIDDEN_INPUT, true)} + + )} + + ) + })} + + ) +} diff --git a/src/view/com/composer/event/EventEditor.tsx b/src/view/com/composer/event/EventEditor.tsx new file mode 100644 index 000000000..09e7976a0 --- /dev/null +++ b/src/view/com/composer/event/EventEditor.tsx @@ -0,0 +1,426 @@ +import {View} from 'react-native' +import {getLocales} from 'expo-localization' +import {Trans, useLingui} from '@lingui/react/macro' +import {useQuery} from '@tanstack/react-query' +import {countGraphemes} from 'unicode-segmenter/grapheme' + +import {getLinkMeta} from '#/lib/link-meta/link-meta' +import {useAgent, useSession} from '#/state/session' +import {EventCoverPicker} from '#/view/com/composer/event/EventCoverPicker' +import {EventDateRange} from '#/view/com/composer/event/EventDateRange' +import {FieldLabelText, INPUT_TEXT} from '#/view/com/composer/event/EventFields' +import {type PostAction} from '#/view/com/composer/state/composer' +import {atoms as a, useTheme} from '#/alf' +import {DEFAULT_BRAND} from '#/alf/themes' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import * as TextField from '#/components/forms/TextField' +import {CalendarDays_Stroke2_Corner0_Rounded as CalendarIcon} from '#/components/icons/CalendarDays' +import {DotGrid3x1_Stroke2_Corner0_Rounded as DotsIcon} from '#/components/icons/DotGrid' +import {Pencil_Stroke2_Corner0_Rounded as PencilIcon} from '#/components/icons/Pencil' +import {Trash_Stroke2_Corner0_Rounded as TrashIcon} from '#/components/icons/Trash' +import * as Menu from '#/components/Menu' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' +import {EventEmbedCard} from '#/features/events/components/EventEmbed' +import { + areEventDetailsValid, + buildEventRecord, + changeEventTime, + deviceTimeZone, + EVENT_DESCRIPTION_MAX_GRAPHEMES, + EVENT_NAME_MAX_GRAPHEMES, + type EventDraft, + type EventDraftFields, + type EventDraftStep, + eventEndsBeforeStart, + eventLocationUrl, + eventStartsInPast, +} from '#/features/events/draft' +import {parseEventRecord} from '#/features/events/record' +import {eventAtUri} from '#/features/events/url' + +const STEPS: EventDraftStep[] = ['details', 'when', 'cover'] + +export function EventEditor({ + event, + dispatch, +}: { + event: EventDraft + dispatch: (action: PostAction) => void +}) { + const t = useTheme() + const {t: l} = useLingui() + const ax = useAnalytics() + const stepIndex = STEPS.indexOf(event.step) + const update = (fields: Partial) => + dispatch({type: 'embed_update_event', fields}) + const setStep = (step: EventDraftStep) => + dispatch({type: 'embed_set_event_step', step}) + const canContinue = + event.step === 'details' + ? areEventDetailsValid(event) + : event.step === 'when' + ? !eventEndsBeforeStart(event) + : true + const isLastStep = stepIndex === STEPS.length - 1 + const stepColor = + t.name === 'light' ? t.palette.primary_500 : DEFAULT_BRAND.secondary + const remove = () => { + ax.metric('composer:event:remove', {}) + dispatch({type: 'embed_remove_event'}) + } + const linkImage = useLinkImage( + event.step === 'cover' && !event.cover && !event.coverRemoved + ? eventLocationUrl(event) + : undefined, + ) + const cover = + coverUri(event.cover) ?? (event.coverRemoved ? undefined : linkImage) + + return ( + + + + + + + Event + + + + {event.step === 'done' ? ( + + + {({props}) => ( + + )} + + + + setStep('details')}> + + Edit event + + + + + + Delete event + + + + + + + ) : ( + + )} + + + {event.step === 'details' && ( + + )} + {event.step === 'when' && } + {event.step === 'cover' && ( + + + Select the event image + + + + update( + image + ? { + cover: { + path: image.path, + mime: image.mime, + width: image.width, + height: image.height, + }, + coverRemoved: false, + } + : {cover: undefined, coverRemoved: true}, + ) + } + /> + + + )} + {event.step === 'done' && } + + {stepIndex >= 0 && ( + + + + + + Step {stepIndex + 1} of {STEPS.length} + + + + + {stepIndex > 0 && ( + + )} + + + + )} + + ) +} + +function DetailsStep({ + event, + update, +}: { + event: EventDraft + update: (fields: Partial) => void +}) { + const {t: l} = useLingui() + const nameCount = countGraphemes(event.name.trim()) + const descriptionCount = countGraphemes(event.description.trim()) + + return ( + + + + Create your event + + EVENT_NAME_MAX_GRAPHEMES}> + update({name})} + style={INPUT_TEXT} + /> + + + + + + Describe your event (optional) + + EVENT_DESCRIPTION_MAX_GRAPHEMES}> + update({description})} + style={INPUT_TEXT} + multiline + /> + + + + + ) +} + +function WhenStep({ + event, + update, +}: { + event: EventDraft + update: (fields: Partial) => void +}) { + const t = useTheme() + const {t: l} = useLingui() + const endsBeforeStart = eventEndsBeforeStart(event) + const startsInPast = eventStartsInPast(event) + + return ( + + + + Add location + + + update({location})} + style={INPUT_TEXT} + /> + + + update(changeEventTime(event, field, iso))} + /> + {endsBeforeStart ? ( + + The end date must be after the start date. + + ) : startsInPast ? ( + + This event starts in the past. + + ) : null} + + ) +} + +function Counter({count, max}: {count: number; max: number}) { + const t = useTheme() + return ( + max + ? {color: t.palette.negative_500} + : t.atoms.text_contrast_medium, + ]}> + {`${count} / ${max}`} + + ) +} + +function useLinkImage(url: string | undefined) { + const agent = useAgent() + const {data} = useQuery({ + queryKey: ['event-cover-link-image', url], + queryFn: async () => (await getLinkMeta(agent, url!)).image ?? null, + enabled: !!url, + staleTime: Infinity, + }) + return data ?? undefined +} + +function EventPreview({event}: {event: EventDraft}) { + const {t: l} = useLingui() + const {currentAccount} = useSession() + if (!currentAccount) return null + const record = buildEventRecord(event, { + now: new Date(), + timeZone: deviceTimeZone(), + country: getLocales()[0]?.regionCode ?? undefined, + }) + const parsed = parseEventRecord(record) + if (!parsed) return null + return ( + + + + ) +} + +function coverUri(cover: EventDraft['cover']) { + return cover && ('url' in cover ? cover.url : cover.path) +} diff --git a/src/view/com/composer/event/EventFields.tsx b/src/view/com/composer/event/EventFields.tsx new file mode 100644 index 000000000..45d296f1f --- /dev/null +++ b/src/view/com/composer/event/EventFields.tsx @@ -0,0 +1,42 @@ +import {type ReactNode} from 'react' +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import {Text} from '#/components/Typography' + +export const INPUT_TEXT = [a.text_lg, {lineHeight: 22}] + +export function FieldLabelText({children}: {children: ReactNode}) { + const t = useTheme() + return ( + + {children} + + ) +} + +export function DateBox({iso, isInvalid}: {iso: string; isInvalid?: boolean}) { + const t = useTheme() + const {i18n} = useLingui() + const date = new Date(iso) + return ( + + + {`${i18n.date(date, {dateStyle: 'medium'})},\n${i18n.date(date, { + timeStyle: 'short', + })}`} + + + ) +} diff --git a/src/view/com/composer/event/SelectEventBtn.tsx b/src/view/com/composer/event/SelectEventBtn.tsx new file mode 100644 index 000000000..e3bd4f9a4 --- /dev/null +++ b/src/view/com/composer/event/SelectEventBtn.tsx @@ -0,0 +1,40 @@ +import {useLingui} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import {Button} from '#/components/Button' +import {CalendarDays_Stroke2_Corner0_Rounded as CalendarIcon} from '#/components/icons/CalendarDays' +import {useAnalytics} from '#/analytics' + +export function SelectEventBtn({ + onPress, + disabled, +}: { + onPress: () => void + disabled?: boolean +}) { + const ax = useAnalytics() + const {t: l} = useLingui() + const t = useTheme() + + return ( + + ) +} diff --git a/src/view/com/composer/event/__tests__/EventDateRange.web.test.tsx b/src/view/com/composer/event/__tests__/EventDateRange.web.test.tsx new file mode 100644 index 000000000..365bb3480 --- /dev/null +++ b/src/view/com/composer/event/__tests__/EventDateRange.web.test.tsx @@ -0,0 +1,79 @@ +import {fireEvent, render} from '@testing-library/react-native' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: (message: {message?: string} | string) => + typeof message === 'string' ? message : (message.message ?? ''), + }), +})) +jest.mock('#/alf', () => { + const blank = new Proxy({}, {get: () => ({})}) + return { + atoms: blank, + useTheme: () => ({ + atoms: blank, + palette: new Proxy({}, {get: (target, key) => String(key)}), + scheme: 'dark', + }), + } +}) +jest.mock('../EventFields', () => ({ + DateBox: () => null, + FieldLabelText: () => null, +})) + +import {EventDateRange} from '../EventDateRange.web' + +const props = { + startsAt: '2027-01-15T11:05:00.000Z', + endsAt: '2027-01-15T12:05:00.000Z', + isEndInvalid: false, + onChange: jest.fn(), +} + +function withInputPrototype(prototype: object) { + ;(globalThis as unknown as {HTMLInputElement: unknown}).HTMLInputElement = { + prototype, + } +} + +describe('EventDateRange on web', () => { + afterEach(() => { + delete (globalThis as unknown as {HTMLInputElement?: unknown}) + .HTMLInputElement + }) + + it('opens the browser picker from the styled boxes when it can', () => { + withInputPrototype({showPicker() {}}) + const {getAllByRole} = render() + expect(getAllByRole('button')).toHaveLength(2) + }) + + it('shows the date inputs directly when the browser has no picker API', () => { + withInputPrototype({}) + const {queryAllByRole, UNSAFE_getAllByType} = render( + , + ) + expect(queryAllByRole('button')).toHaveLength(0) + const [start] = UNSAFE_getAllByType('input' as never) as unknown as { + props: {tabIndex?: number} + }[] + expect(start.props.tabIndex).toBeUndefined() + }) + + it('falls back to the date inputs when opening the picker fails', () => { + withInputPrototype({showPicker() {}}) + const {getAllByRole, queryAllByRole} = render( + , + { + createNodeMock: () => ({ + showPicker() { + throw new Error('not supported') + }, + }), + }, + ) + fireEvent.press(getAllByRole('button')[0]) + expect(queryAllByRole('button')).toHaveLength(0) + }) +}) diff --git a/src/view/com/composer/event/__tests__/EventEditor.test.tsx b/src/view/com/composer/event/__tests__/EventEditor.test.tsx new file mode 100644 index 000000000..8e419cfcc --- /dev/null +++ b/src/view/com/composer/event/__tests__/EventEditor.test.tsx @@ -0,0 +1,418 @@ +import {useReducer} from 'react' +import {fireEvent, render} from '@testing-library/react-native' + +import { + composerReducer, + type ComposerState, + createComposerState, +} from '#/view/com/composer/state/composer' + +jest.mock('@lingui/react', () => { + const format = ( + message: + | {message?: string; values?: Record} + | string, + ) => { + if (typeof message === 'string') return message + return (message.message ?? '').replace(/{(\w+)}/g, (_, key: string) => + String(message.values?.[key] ?? ''), + ) + } + return { + useLingui: () => ({_: format, i18n: {locale: 'en-US'}}), + Trans: ({ + id, + message, + values, + }: { + id: string + message?: string + values?: Record + }) => format({message: message ?? id, values}), + } +}) +jest.mock('#/alf', () => { + const blank = new Proxy({}, {get: () => ({})}) + return { + atoms: blank, + useTheme: () => ({ + atoms: blank, + palette: new Proxy({}, {get: (target, key) => String(key)}), + }), + } +}) +jest.mock('#/alf/themes', () => ({DEFAULT_BRAND: {secondary: '#D2FC51'}})) +jest.mock('#/components/Typography', () => { + const {Text} = require('react-native') + return {Text} +}) +jest.mock('#/components/icons/CalendarDays', () => ({ + CalendarDays_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/Button', () => { + const {Pressable, Text} = require('react-native') + return { + Button: ({ + children, + disabled, + label, + onPress, + testID, + }: { + children: React.ReactNode + disabled?: boolean + label: string + onPress: () => void + testID?: string + }) => ( + + {children} + + ), + ButtonText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + ButtonIcon: () => null, + } +}) +jest.mock('#/components/forms/TextField', () => { + const {Text, TextInput} = require('react-native') + return { + Root: ({children}: {children: React.ReactNode}) => children, + LabelText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + Input: ({ + label, + onChangeText, + testID, + value, + }: { + label: string + onChangeText: (text: string) => void + testID: string + value: string + }) => ( + + ), + } +}) + +const mockMetric = jest.fn() +jest.mock('#/analytics', () => ({ + useAnalytics: () => ({metric: mockMetric}), +})) +jest.mock('#/lib/api/community-feed', () => ({ + isSpaceBackedFeed: (config: {space?: string} | undefined) => !!config?.space, +})) +jest.mock('#/state/gallery', () => ({createInitialImages: jest.fn()})) +jest.mock('#/state/queries/threadgate', () => ({ + threadgateRecordToAllowUISetting: jest.fn(() => []), +})) +jest.mock('#/view/com/composer/state/video', () => ({ + createVideoState: jest.fn(), + videoReducer: jest.fn(), +})) + +jest.mock('../EventDateRange', () => { + const {Pressable} = require('react-native') + return { + EventDateRange: ({ + onChange, + }: { + onChange: (field: string, iso: string) => void + }) => ( + onChange('endsAt', '2000-01-01T00:00:00.000Z')} + /> + ), + } +}) + +const mockLinkImage = jest.fn() +jest.mock('@tanstack/react-query', () => ({ + useQuery: ({enabled}: {enabled: boolean}) => ({ + data: enabled ? mockLinkImage() : undefined, + }), +})) +jest.mock('#/state/session', () => ({ + useAgent: () => ({}), + useSession: () => ({ + currentAccount: {did: 'did:plc:me', handle: 'me.test'}, + }), +})) +jest.mock('#/components/Menu', () => { + const {Pressable, Text, View} = require('react-native') + return { + Root: ({children}: {children: React.ReactNode}) => {children}, + Outer: ({children}: {children: React.ReactNode}) => {children}, + Group: ({children}: {children: React.ReactNode}) => {children}, + Trigger: ({ + children, + }: { + children: (p: {props: {accessibilityLabel: string}}) => React.ReactNode + }) => children({props: {accessibilityLabel: 'Event options'}}), + Item: ({ + children, + label, + onPress, + testID, + }: { + children: React.ReactNode + label: string + onPress: () => void + testID: string + }) => ( + + {children} + + ), + ItemText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + ItemIcon: () => null, + } +}) +jest.mock('#/features/events/components/EventEmbed', () => { + const {Text} = require('react-native') + return { + EventEmbedCard: ({ + event, + parsed, + }: { + event: {thumb?: string} + parsed: {name: string; location?: string} + }) => ( + + {[parsed.name, parsed.location ?? '', event.thumb ?? ''].join('|')} + + ), + } +}) +jest.mock('#/lib/link-meta/link-meta', () => ({getLinkMeta: jest.fn()})) +jest.mock('../EventCoverPicker', () => { + const {Pressable, Text, View} = require('react-native') + return { + EventCoverPicker: ({ + cover: banner, + onChange: onSelectNewBanner, + }: { + cover?: string + onChange: (image: unknown) => void + }) => ( + + {banner ?? 'none'} + + onSelectNewBanner({ + path: 'file:///picked.jpg', + mime: 'image/jpeg', + width: 1500, + height: 500, + size: 1, + }) + } + /> + onSelectNewBanner(null)} + /> + + ), + } +}) + +import {EventEditor} from '../EventEditor' + +function composerWithEvent(): ComposerState { + const state = createComposerState({ + initText: undefined, + initMention: undefined, + initImageUris: undefined, + initQuoteUri: undefined, + initInteractionSettings: undefined, + }) + return composerReducer(state, { + type: 'update_post', + postId: state.thread.posts[0].id, + postAction: {type: 'embed_add_event'}, + }) +} + +function Harness() { + const [state, dispatch] = useReducer( + composerReducer, + undefined, + composerWithEvent, + ) + const post = state.thread.posts[0] + if (!post.embed.event) return null + const {Text} = require('react-native') + return ( + <> + + dispatch({type: 'update_post', postId: post.id, postAction}) + } + /> + + {JSON.stringify(post.embed.event.cover ?? null)} + + + ) +} + +describe('EventEditor', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('needs a name before continuing', () => { + const {getByTestId} = render() + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 1 of 3') + + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 1 of 3') + + fireEvent.changeText(getByTestId('eventNameInput'), 'Party') + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 2 of 3') + }) + + it('has no back button on the first step', () => { + const {queryByTestId} = render() + expect(queryByTestId('eventBackBtn')).toBeNull() + }) + + it('walks through the steps, back and forth, to the finished event', () => { + const {getByTestId, queryByTestId, getByText} = render() + fireEvent.changeText(getByTestId('eventNameInput'), 'Party') + fireEvent.press(getByTestId('eventContinueBtn')) + fireEvent.changeText(getByTestId('eventLocationInput'), 'The park') + fireEvent.press(getByTestId('eventBackBtn')) + expect(getByTestId('eventNameInput')).toHaveProp('value', 'Party') + + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('eventLocationInput')).toHaveProp('value', 'The park') + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 3 of 3') + expect(getByTestId('eventContinueBtn')).toHaveProp( + 'accessibilityLabel', + 'Create event', + ) + + fireEvent.press(getByTestId('eventContinueBtn')) + expect(queryByTestId('eventStepLabel')).toBeNull() + expect(queryByTestId('removeEventBtn')).toBeNull() + expect(getByText(/^Party\|/)).toBeTruthy() + + fireEvent.press(getByTestId('editEventBtn')) + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 1 of 3') + }) + + it('previews the finished event from the record that will be saved', () => { + mockLinkImage.mockReturnValue('https://example.com/og.jpg') + const {getByTestId} = toCoverStep('https://twitch.tv/someone') + fireEvent.press(getByTestId('eventContinueBtn')) + + expect(getByTestId('previewCard')).toHaveTextContent( + 'Party||https://example.com/og.jpg', + ) + }) + + it('deletes the finished event from its menu', () => { + const {getByTestId, queryByTestId} = toCoverStep('Prospect Park') + fireEvent.press(getByTestId('eventContinueBtn')) + fireEvent.press(getByTestId('deleteEventBtn')) + expect(queryByTestId('eventEditor')).toBeNull() + expect(mockMetric).toHaveBeenCalledWith('composer:event:remove', {}) + }) + + it('removes the event', () => { + const {getByTestId, queryByTestId} = render() + fireEvent.press(getByTestId('removeEventBtn')) + expect(queryByTestId('eventEditor')).toBeNull() + expect(mockMetric).toHaveBeenCalledWith('composer:event:remove', {}) + }) + + it('blocks continuing when the end is before the start', () => { + const {getByTestId, getByText} = render() + fireEvent.changeText(getByTestId('eventNameInput'), 'Party') + fireEvent.press(getByTestId('eventContinueBtn')) + fireEvent.press(getByTestId('setEndBeforeStart')) + + expect(getByText('The end date must be after the start date.')).toBeTruthy() + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('eventStepLabel')).toHaveTextContent('Step 2 of 3') + }) + + function toCoverStep(location: string) { + const utils = render() + fireEvent.changeText(utils.getByTestId('eventNameInput'), 'Party') + fireEvent.press(utils.getByTestId('eventContinueBtn')) + fireEvent.changeText(utils.getByTestId('eventLocationInput'), location) + fireEvent.press(utils.getByTestId('eventContinueBtn')) + return utils + } + + it("defaults the cover to the link's image and keeps it on create", () => { + mockLinkImage.mockReturnValue('https://example.com/og.jpg') + const {getByTestId} = toCoverStep('https://twitch.tv/someone') + + expect(getByTestId('coverShown')).toHaveTextContent( + 'https://example.com/og.jpg', + ) + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('draftCover')).toHaveTextContent( + JSON.stringify({url: 'https://example.com/og.jpg'}), + ) + }) + + it('lets a picked photo replace the default, and removal clear it', () => { + mockLinkImage.mockReturnValue('https://example.com/og.jpg') + const {getByTestId} = toCoverStep('https://twitch.tv/someone') + + fireEvent.press(getByTestId('pickCover')) + expect(getByTestId('coverShown')).toHaveTextContent('file:///picked.jpg') + + fireEvent.press(getByTestId('removeCover')) + expect(getByTestId('coverShown')).toHaveTextContent('none') + fireEvent.press(getByTestId('eventContinueBtn')) + expect(getByTestId('draftCover')).toHaveTextContent('null') + }) + + it('looks up no link image for an in-person place', () => { + const {getByTestId} = toCoverStep('Prospect Park') + expect(mockLinkImage).not.toHaveBeenCalled() + expect(getByTestId('coverShown')).toHaveTextContent('none') + }) +}) diff --git a/src/view/com/composer/photos/EditImageDialog.tsx b/src/view/com/composer/photos/EditImageDialog.tsx index 9a0eb9084..f0459efb5 100644 --- a/src/view/com/composer/photos/EditImageDialog.tsx +++ b/src/view/com/composer/photos/EditImageDialog.tsx @@ -7,6 +7,7 @@ export type EditImageDialogProps = { onChange: (next: ComposerImage) => void aspectRatio?: number circularCrop?: boolean + preselectCrop?: boolean } export const EditImageDialog = ({}: EditImageDialogProps): React.ReactNode => { diff --git a/src/view/com/composer/photos/EditImageDialog.web.tsx b/src/view/com/composer/photos/EditImageDialog.web.tsx index 60f4fc1fa..e6abc7151 100644 --- a/src/view/com/composer/photos/EditImageDialog.web.tsx +++ b/src/view/com/composer/photos/EditImageDialog.web.tsx @@ -5,7 +5,11 @@ import {View} from 'react-native' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' -import ReactCrop, {type PercentCrop} from 'react-image-crop' +import ReactCrop, { + centerCrop, + makeAspectCrop, + type PercentCrop, +} from 'react-image-crop' import { type ImageSource, @@ -33,6 +37,7 @@ function DialogInner({ onChange, circularCrop, aspectRatio, + preselectCrop, }: EditImageDialogProps) { const {_} = useLingui() const [pending, setPending] = useState(false) @@ -99,6 +104,7 @@ function DialogInner({ onChange={onChange} circularCrop={circularCrop} aspectRatio={aspectRatio} + preselectCrop={preselectCrop} /> )} @@ -111,6 +117,7 @@ function EditImageInner({ saveRef, circularCrop = false, aspectRatio, + preselectCrop, }: Required> & Omit & { saveRef: React.RefObject<{save: () => Promise} | null> @@ -121,7 +128,11 @@ function EditImageInner({ const source = image.source - const initialCrop = getInitialCrop(source, image.manips) + const initialCrop = + getInitialCrop(source, image.manips) ?? + (preselectCrop && aspectRatio + ? centeredCrop(source, aspectRatio) + : undefined) const [crop, setCrop] = useState(initialCrop) const onPressSubmit = useCallback(async () => { @@ -193,3 +204,17 @@ const getInitialCrop = ( } } } + +const centeredCrop = (source: ImageSource, aspect: number): PercentCrop => + centerCrop( + makeAspectCrop( + source.width / source.height > aspect + ? {unit: '%', height: 100} + : {unit: '%', width: 100}, + aspect, + source.width, + source.height, + ), + source.width, + source.height, + ) diff --git a/src/view/com/composer/state/__tests__/composer-event.test.ts b/src/view/com/composer/state/__tests__/composer-event.test.ts new file mode 100644 index 000000000..7d3ee4ba4 --- /dev/null +++ b/src/view/com/composer/state/__tests__/composer-event.test.ts @@ -0,0 +1,249 @@ +import {type ComposerImage} from '#/state/gallery' +import {type Gif} from '#/features/gifPicker/types' +import { + type ComposerAction, + composerReducer, + type ComposerState, + createComposerState, + isEventPostable, + postHasAttachment, + threadHasEvent, +} from '../composer' + +jest.mock('#/lib/api/community-feed', () => ({ + isSpaceBackedFeed: (config: {space?: string} | undefined) => !!config?.space, +})) +jest.mock('#/state/gallery', () => ({createInitialImages: jest.fn()})) +jest.mock('#/state/queries/threadgate', () => ({ + threadgateRecordToAllowUISetting: jest.fn(() => []), +})) +jest.mock('../video', () => ({ + createVideoState: jest.fn(() => ({abortController: new AbortController()})), + videoReducer: jest.fn(), +})) + +const image = { + source: { + id: 'img-1', + path: 'file://a', + mime: 'image/jpeg', + width: 1, + height: 1, + }, +} as unknown as ComposerImage + +type PostAction = Extract['postAction'] + +function initialState(): ComposerState { + return createComposerState({ + initText: undefined, + initMention: undefined, + initImageUris: undefined, + initQuoteUri: undefined, + initInteractionSettings: undefined, + }) +} + +function updatePost( + state: ComposerState, + index: number, + postAction: PostAction, +): ComposerState { + return composerReducer(state, { + type: 'update_post', + postId: state.thread.posts[index].id, + postAction, + }) +} + +function apply(state: ComposerState, actions: PostAction[]): ComposerState { + return actions.reduce((next, action) => updatePost(next, 0, action), state) +} + +function draftAfter(actions: PostAction[]) { + return apply(initialState(), actions).thread.posts[0] +} + +const named: PostAction = {type: 'embed_update_event', fields: {name: 'Party'}} + +describe('composer events', () => { + beforeEach(() => { + jest.useFakeTimers().setSystemTime(new Date('2027-01-15T11:05:42.123Z')) + }) + afterEach(() => { + jest.useRealTimers() + }) + + it('adds an event at the first step, starting and ending now', () => { + const post = draftAfter([{type: 'embed_add_event'}]) + expect(post.embed.event).toEqual({ + step: 'details', + name: '', + description: '', + location: '', + startsAt: '2027-01-15T11:05:00.000Z', + endsAt: '2027-01-15T11:05:00.000Z', + }) + expect(postHasAttachment(post)).toBe(true) + }) + + it('updates fields and steps, and removes the event', () => { + let state = apply(initialState(), [ + {type: 'embed_add_event'}, + named, + {type: 'embed_update_event', fields: {location: 'The park'}}, + {type: 'embed_set_event_step', step: 'when'}, + ]) + expect(state.thread.posts[0].embed.event).toMatchObject({ + step: 'when', + name: 'Party', + location: 'The park', + }) + state = apply(state, [{type: 'embed_remove_event'}]) + expect(state.thread.posts[0].embed.event).toBeUndefined() + }) + + it('ignores updates when there is no event', () => { + const post = draftAfter([ + named, + {type: 'embed_set_event_step', step: 'done'}, + ]) + expect(post.embed.event).toBeUndefined() + }) + + it('is not added next to another attachment', () => { + const post = draftAfter([ + {type: 'embed_add_images', images: [image]}, + {type: 'embed_add_event'}, + ]) + expect(post.embed.event).toBeUndefined() + }) + + it('is not added next to a poll', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_add_event'}, + ]) + expect(post.embed.event).toBeUndefined() + }) + + it('keeps other attachments out once added', () => { + const post = draftAfter([ + {type: 'embed_add_event'}, + {type: 'embed_add_images', images: [image]}, + {type: 'embed_add_uri', uri: 'https://example.com'}, + {type: 'embed_add_gif', gif: {} as Gif}, + {type: 'embed_add_poll'}, + ]) + expect(post.embed.media).toBeUndefined() + expect(post.embed.link).toBeUndefined() + expect(post.embed.poll).toBeUndefined() + expect(post.embed.event).toBeDefined() + }) + + it('allows one event per thread', () => { + let state = composerReducer(initialState(), {type: 'add_post'}) + state = updatePost(state, 0, {type: 'embed_add_event'}) + state = updatePost(state, 1, {type: 'embed_add_event'}) + expect(state.thread.posts[0].embed.event).toBeDefined() + expect(state.thread.posts[1].embed.event).toBeUndefined() + expect(threadHasEvent(state.thread)).toBe(true) + }) + + it('is not added to a Blacksky-only post', () => { + let state = composerReducer(initialState(), {type: 'toggle_blacksky_only'}) + state = updatePost(state, 0, {type: 'embed_add_event'}) + expect(state.thread.posts[0].embed.event).toBeUndefined() + }) + + it('is not added to a thread quoting a community post', () => { + let state = updatePost(initialState(), 0, { + type: 'embed_add_uri', + uri: 'https://bsky.app/profile/did:plc:author/post/3kabc?collection=community.blacksky.feed.post', + }) + state = composerReducer(state, {type: 'add_post'}) + state = updatePost(state, 1, {type: 'embed_add_event'}) + expect(state.thread.posts[1].embed.event).toBeUndefined() + }) + + it('is cleared when the post moves off the public target', () => { + let state = updatePost(initialState(), 0, {type: 'embed_add_event'}) + state = composerReducer(state, { + type: 'set_post_target', + target: 'blacksky', + }) + expect(state.thread.posts[0].embed.event).toBeUndefined() + }) + + it('keeps only the first event when restoring a draft', () => { + const two = composerReducer(initialState(), {type: 'add_post'}) + const draft = apply(initialState(), [{type: 'embed_add_event'}]).thread + .posts[0].embed.event! + const posts = two.thread.posts.map(p => ({ + ...p, + embed: {...p.embed, event: draft}, + })) + const restored = composerReducer(initialState(), { + type: 'restore_from_draft', + draftId: 'd1', + posts, + threadgateAllow: undefined, + postgateEmbeddingRules: undefined, + loadedMedia: new Map(), + originalLocalRefs: new Set(), + }) + expect(restored.thread.posts.map(p => !!p.embed.event)).toEqual([ + true, + false, + ]) + }) + + describe('isEventPostable', () => { + it('is true without an event', () => { + expect(isEventPostable(draftAfter([]))).toBe(true) + }) + + it('needs the steps finished', () => { + expect( + isEventPostable(draftAfter([{type: 'embed_add_event'}, named])), + ).toBe(false) + expect( + isEventPostable( + draftAfter([ + {type: 'embed_add_event'}, + named, + {type: 'embed_set_event_step', step: 'done'}, + ]), + ), + ).toBe(true) + }) + + it('needs a name', () => { + expect( + isEventPostable( + draftAfter([ + {type: 'embed_add_event'}, + {type: 'embed_update_event', fields: {name: ' '}}, + {type: 'embed_set_event_step', step: 'done'}, + ]), + ), + ).toBe(false) + }) + + it('refuses an end before the start', () => { + expect( + isEventPostable( + draftAfter([ + {type: 'embed_add_event'}, + named, + { + type: 'embed_update_event', + fields: {endsAt: '2027-01-15T10:00:00.000Z'}, + }, + {type: 'embed_set_event_step', step: 'done'}, + ]), + ), + ).toBe(false) + }) + }) +}) diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index 64aeedb5d..42349720b 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -39,6 +39,13 @@ import { type LinkFacetMatch, suggestLinkCardUri, } from '#/view/com/composer/text-input/text-input-util' +import { + createEventDraft, + type EventDraft, + type EventDraftFields, + type EventDraftStep, + isEventDraftPublishable, +} from '#/features/events/draft' import {type Gif} from '#/features/gifPicker/types' import { createVideoState, @@ -82,6 +89,7 @@ export type EmbedDraft = { // This field may end up ignored if we have more important things to display than a link card: link: Link | undefined poll?: PollDraft + event?: EventDraft } export type PostDraft = { @@ -117,13 +125,27 @@ export type PostAction = | {type: 'embed_remove_poll_statement'; index: number} | {type: 'embed_set_poll_assembly'; assembly: AssemblyRef} | {type: 'embed_remove_poll'} + | {type: 'embed_add_event'} + | {type: 'embed_update_event'; fields: Partial} + | {type: 'embed_set_event_step'; step: EventDraftStep} + | {type: 'embed_remove_event'} export function postHasAttachment(post: PostDraft): boolean { return Boolean( - post.embed.media || post.embed.link || post.embed.quote || post.embed.poll, + post.embed.media || + post.embed.link || + post.embed.quote || + post.embed.poll || + post.embed.event, ) } +// A poll or an event fills the post's only external embed, so nothing else +// can be attached alongside it. +function hasExclusiveEmbed(embed: EmbedDraft): boolean { + return !!(embed.poll || embed.event) +} + export function postHasContent(post: PostDraft): boolean { return post.richtext.text.trim().length > 0 || postHasAttachment(post) } @@ -140,6 +162,17 @@ export function isPollPostable(post: PostDraft): boolean { ) } +export function isEventPostable(post: PostDraft): boolean { + const event = post.embed.event + if (!event) return true + return ( + isEventDraftPublishable(event) && + !post.embed.media && + !post.embed.link && + !post.embed.quote + ) +} + export type ThreadDraft = { posts: PostDraft[] postgate: AppBskyFeedPostgate.Record @@ -263,11 +296,19 @@ export function threadHasPoll(thread: ThreadDraft): boolean { return thread.posts.some(post => post.embed.poll) } -function keepFirstPoll(posts: PostDraft[]): PostDraft[] { - const first = posts.findIndex(post => post.embed.poll) +export const isEventAllowed = isPollAllowed + +export function threadHasEvent(thread: ThreadDraft): boolean { + return thread.posts.some(post => post.embed.event) +} + +function keepFirst(posts: PostDraft[], key: 'poll' | 'event'): PostDraft[] { + const first = posts.findIndex(post => post.embed[key]) return posts.map((post, index) => - post.embed.poll && index !== first - ? postReducer(post, {type: 'embed_remove_poll'}) + post.embed[key] && index !== first + ? postReducer(post, { + type: key === 'poll' ? 'embed_remove_poll' : 'embed_remove_event', + }) : post, ) } @@ -279,7 +320,8 @@ function applyTargetChange( const clearVideos = hasSpaceVideoTarget(state.thread) !== hasSpaceVideoTarget(nextThread) const clearPolls = threadHasPoll(nextThread) && !isPublicTarget(nextThread) - if (!clearVideos && !clearPolls) { + const clearEvents = threadHasEvent(nextThread) && !isPublicTarget(nextThread) + if (!clearVideos && !clearPolls && !clearEvents) { return { ...state, isDirty: true, @@ -292,9 +334,13 @@ function applyTargetChange( clearVideos && post.embed.media?.type === 'video' ? postReducer(post, {type: 'embed_remove_video'}) : post - return clearPolls && withoutVideo.embed.poll - ? postReducer(withoutVideo, {type: 'embed_remove_poll'}) - : withoutVideo + const withoutPoll = + clearPolls && withoutVideo.embed.poll + ? postReducer(withoutVideo, {type: 'embed_remove_poll'}) + : withoutVideo + return clearEvents && withoutPoll.embed.event + ? postReducer(withoutPoll, {type: 'embed_remove_event'}) + : withoutPoll }) return { ...state, @@ -392,6 +438,13 @@ export function composerReducer( ) { return state } + if ( + action.postAction.type === 'embed_add_event' && + (threadHasEvent(state.thread) || + !isEventAllowed(state.thread, undefined)) + ) { + return state + } let nextPosts = state.thread.posts const postIndex = state.thread.posts.findIndex( p => p.id === action.postId, @@ -493,7 +546,7 @@ export function composerReducer( loadedMediaMap: loadedMedia, originalLocalRefs, thread: { - posts: keepFirstPoll(posts), + posts: keepFirst(keepFirst(posts, 'poll'), 'event'), postgate: createPostgateRecord({ post: '', embeddingRules: postgateEmbeddingRules, @@ -543,7 +596,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_images': { - if (action.images.length === 0 || state.embed.poll) { + if (action.images.length === 0 || hasExclusiveEmbed(state.embed)) { return state } const prevMedia = state.embed.media @@ -629,7 +682,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { return state } case 'embed_add_video': { - if (state.embed.poll) { + if (hasExclusiveEmbed(state.embed)) { return state } const prevMedia = state.embed.media @@ -682,7 +735,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_uri': { - if (state.embed.poll) { + if (hasExclusiveEmbed(state.embed)) { return state } const prevQuote = state.embed.quote @@ -732,7 +785,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_gif': { - if (state.embed.poll) { + if (hasExclusiveEmbed(state.embed)) { return state } const prevMedia = state.embed.media @@ -864,6 +917,41 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { }, } } + case 'embed_add_event': { + if (postHasAttachment(state)) { + return state + } + return { + ...state, + embed: {...state.embed, event: createEventDraft()}, + } + } + case 'embed_update_event': { + const event = state.embed.event + if (!event) { + return state + } + return { + ...state, + embed: {...state.embed, event: {...event, ...action.fields}}, + } + } + case 'embed_set_event_step': { + const event = state.embed.event + if (!event) { + return state + } + return { + ...state, + embed: {...state.embed, event: {...event, step: action.step}}, + } + } + case 'embed_remove_event': { + return { + ...state, + embed: {...state.embed, event: undefined}, + } + } } } -- knotmirror 0.0.1 From 65c7951c590468c48d18c22b3dc0ad5d7d18f71c Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Tue, 10 Nov 2026 14:13:56 -0500 Subject: [PATCH 2/2] fix(links): open the group invite dialog when an in-app /join link is tapped (#232) --- src/components/Link.tsx | 14 +++++++++++++- src/view/com/util/Link.tsx | 18 +++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/components/Link.tsx b/src/components/Link.tsx index 0818b2a26..db1791d41 100644 --- a/src/components/Link.tsx +++ b/src/components/Link.tsx @@ -13,7 +13,10 @@ import { } from '@react-navigation/native' import {BSKY_DOWNLOAD_URL} from '#/lib/constants' -import {useGroupChatJoinIntent} from '#/lib/hooks/useIntentHandler' +import { + useGroupChatJoinIntent, + useGroupInviteIntent, +} from '#/lib/hooks/useIntentHandler' import {useNavigationDeduped} from '#/lib/hooks/useNavigationDeduped' import {useOpenLink} from '#/lib/hooks/useOpenLink' import {type AllNavigatorParams, type RouteParams} from '#/lib/routes/types' @@ -22,6 +25,7 @@ import { convertBskyAppUrlIfNeeded, createProxiedUrl, getChatInviteCodeFromUrl, + getGroupInviteCodeFromUrl, isBskyDownloadUrl, isExternalUrl, linkRequiresWarning, @@ -142,6 +146,7 @@ export function useLink({ const {linkWarningDialogControl} = useGlobalDialogsControlContext() const openLink = useOpenLink() const groupChatJoinIntent = useGroupChatJoinIntent() + const groupInviteIntent = useGroupInviteIntent() const onPress = useCallback( (e: GestureResponderEvent) => { @@ -166,6 +171,12 @@ export function useLink({ return } + const groupInviteCode = getGroupInviteCodeFromUrl(href) + if (groupInviteCode) { + groupInviteIntent(groupInviteCode) + return + } + if (requiresWarning) { linkWarningDialogControl.open({ displayText, @@ -244,6 +255,7 @@ export function useLink({ shouldProxy, linkWarningDialogControl, groupChatJoinIntent, + groupInviteIntent, ], ) diff --git a/src/view/com/util/Link.tsx b/src/view/com/util/Link.tsx index b2647363e..d760d43e8 100644 --- a/src/view/com/util/Link.tsx +++ b/src/view/com/util/Link.tsx @@ -13,7 +13,10 @@ import { import {sanitizeUrl} from '@braintree/sanitize-url' import {StackActions} from '@react-navigation/native' -import {useGroupChatJoinIntent} from '#/lib/hooks/useIntentHandler' +import { + useGroupChatJoinIntent, + useGroupInviteIntent, +} from '#/lib/hooks/useIntentHandler' import { type DebouncedNavigationProp, useNavigationDeduped, @@ -23,6 +26,7 @@ import {getTabState, TabState} from '#/lib/routes/helpers' import { convertBskyAppUrlIfNeeded, getChatInviteCodeFromUrl, + getGroupInviteCodeFromUrl, isExternalUrl, linkRequiresWarning, } from '#/lib/strings/url-helpers' @@ -82,6 +86,7 @@ export const Link = memo(function Link({ const anchorHref = asAnchor ? sanitizeUrl(href) : undefined const openLink = useOpenLink() const groupChatJoinIntent = useGroupChatJoinIntent() + const groupInviteIntent = useGroupInviteIntent() const onPress = useCallback( (e?: Event) => { @@ -93,6 +98,7 @@ export const Link = memo(function Link({ navigationAction, openLink, groupChatJoinIntent, + groupInviteIntent, e, ) } @@ -104,6 +110,7 @@ export const Link = memo(function Link({ openLink, onBeforePress, groupChatJoinIntent, + groupInviteIntent, ], ) @@ -204,6 +211,7 @@ export const TextLink = memo(function TextLink({ const {linkWarningDialogControl} = useGlobalDialogsControlContext() const openLink = useOpenLink() const groupChatJoinIntent = useGroupChatJoinIntent() + const groupInviteIntent = useGroupInviteIntent() if (!disableMismatchWarning && typeof text !== 'string') { console.error('Unable to detect mismatching label') @@ -246,6 +254,7 @@ export const TextLink = memo(function TextLink({ navigationAction, openLink, groupChatJoinIntent, + groupInviteIntent, e, ) }, @@ -260,6 +269,7 @@ export const TextLink = memo(function TextLink({ openLink, linkWarningDialogControl, groupChatJoinIntent, + groupInviteIntent, ], ) const hrefAttrs = useMemo(() => { @@ -381,6 +391,7 @@ function onPressInner( navigationAction: 'push' | 'replace' | 'navigate' = 'push', openLink: (href: string) => void, groupChatJoinIntent: (code: string, uri?: string) => void, + groupInviteIntent: (code: string) => void, e?: Event, ) { let shouldHandle = false @@ -413,6 +424,11 @@ function onPressInner( groupChatJoinIntent(chatInviteCode, href) return } + const groupInviteCode = getGroupInviteCodeFromUrl(href) + if (groupInviteCode) { + groupInviteIntent(groupInviteCode) + return + } if ( newTab || href.startsWith('http') ||