From 1eea4ff0e45ae2cd67304e4948be7c56c94b8430 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Thu, 5 Nov 2026 12:03:57 -0500 Subject: [PATCH] feat(composer): pick event dates and publish the event with its post Step 2 gets a start/end picker: a bottom sheet with Start and End tabs on native, datetime-local inputs on web. Moving the start past the end moves the end with it. Posting writes the community.lexicon.calendar.event record and the post in one applyWrites, so a failed post leaves no event behind. The post carries a link card to the event page. validate is left unset when an event is in the batch, since PDSes refuse unknown lexicons under validate: true. The record stores the device timezone; a link location becomes an online event, and a place becomes an address with the device region as its country. A successful post logs event:create. --- src/analytics/metrics/types.ts | 5 + src/features/events/__tests__/draft.test.ts | 121 ++++++++++++++ src/features/events/draft.ts | 115 ++++++++++++++ src/lib/api/__tests__/event-publish.test.ts | 149 ++++++++++++++++++ src/lib/api/index.ts | 62 +++++++- src/view/com/composer/Composer.tsx | 8 + .../com/composer/event/EventDateRange.tsx | 122 ++++++++++++++ .../composer/event/EventDateRange.types.ts | 8 + .../com/composer/event/EventDateRange.web.tsx | 54 +++++++ src/view/com/composer/event/EventEditor.tsx | 33 ++-- .../event/__tests__/EventEditor.test.tsx | 30 ++++ 11 files changed, 675 insertions(+), 32 deletions(-) create mode 100644 src/lib/api/__tests__/event-publish.test.ts create mode 100644 src/view/com/composer/event/EventDateRange.tsx create mode 100644 src/view/com/composer/event/EventDateRange.types.ts create mode 100644 src/view/com/composer/event/EventDateRange.web.tsx diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 9482c10f7..b348b252c 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -1177,6 +1177,11 @@ export type Events = { 'share:press:recentDm': {} 'share:press:embed': {} + 'event:create': { + uri: string + hasDescription: boolean + hasLocation: 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 index 708b0bb87..e7074c57a 100644 --- a/src/features/events/__tests__/draft.test.ts +++ b/src/features/events/__tests__/draft.test.ts @@ -1,13 +1,19 @@ 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') @@ -76,4 +82,119 @@ describe('event drafts', () => { ), ).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('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('leaves out a place when the country is unknown', () => { + const record = buildEventRecord(draft({location: 'Prospect Park'}), { + now: NOW, + }) + expect(record).not.toHaveProperty('locations') + expect(record).not.toHaveProperty('timezone') + }) + }) + + 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/draft.ts b/src/features/events/draft.ts index d27a9719b..dd9d43586 100644 --- a/src/features/events/draft.ts +++ b/src/features/events/draft.ts @@ -1,5 +1,8 @@ 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 @@ -57,3 +60,115 @@ export function isEventDraftPublishable(draft: EventDraft): boolean { !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 + } +} + +function webUrl(value: string): string | undefined { + try { + const {protocol} = new URL(value) + return protocol === 'http:' || protocol === 'https:' ? value : undefined + } catch { + return undefined + } +} + +export function buildEventRecord( + draft: EventDraft, + {now, timeZone, country}: {now: Date; timeZone?: string; country?: string}, +) { + 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}), + ...(locationUrl + ? { + mode: `${EVENT_COLLECTION}#virtual`, + locations: [{$type: `${EVENT_COLLECTION}#uri`, uri: locationUrl}], + } + : location && country + ? { + mode: `${EVENT_COLLECTION}#inperson`, + locations: [ + { + $type: 'community.lexicon.location.address', + name: location, + 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, + } +} 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..3259eba43 --- /dev/null +++ b/src/lib/api/__tests__/event-publish.test.ts @@ -0,0 +1,149 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {type EventDraft} from '#/features/events/draft' +import {post} from '../index' +import {postToSpace} from '../space-post' + +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()})) + +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() + }) +}) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index cb63fef81..2e4516e16 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,13 @@ import { type PostDraft, type ThreadDraft, } from '#/view/com/composer/state/composer' +import { + buildEventExternal, + buildEventRecord, + deviceTimeZone, +} 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 +107,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 +146,7 @@ export interface PostOpts { export type PostResult = { uris: string[] + event?: {uri: string} assembly?: { conversationId: string statementCount: number @@ -160,6 +175,7 @@ export async function post( ) } refusePoll(thread) + refuseEvent(thread) return postToSpace(agent, queryClient, space, opts) } @@ -184,6 +200,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 +234,7 @@ export async function post( isQuoteOfCommunityPost ) { refusePoll(thread) + refuseEvent(thread) return postCommunity(agent, queryClient, opts) } @@ -236,6 +254,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 @@ -294,12 +315,17 @@ 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', + }), + }) + : resolveEmbed(agent, queryClient, draft, opts.onStateChange) let labels: $Typed | undefined if (draft.labels.length) { labels = { @@ -382,11 +408,27 @@ 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, + }), + }) + } + 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 +452,11 @@ export async function post( ) } - return {uris, assembly} + return { + uris, + assembly, + ...(eventRkey && {event: {uri: eventAtUri(did, eventRkey)}}), + } } async function postCommunity( diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 9288f9663..0788cc48d 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -1112,6 +1112,14 @@ 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, + }) + } /* * Wait for app view to have received the post(s). If this fails, it's diff --git a/src/view/com/composer/event/EventDateRange.tsx b/src/view/com/composer/event/EventDateRange.tsx new file mode 100644 index 000000000..145fddaca --- /dev/null +++ b/src/view/com/composer/event/EventDateRange.tsx @@ -0,0 +1,122 @@ +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 * as TextField from '#/components/forms/TextField' +import {Text} from '#/components/Typography' +import { + type EventTimeField, + formatEventDraftDate, +} from '#/features/events/draft' +import {type EventDateRangeProps} from './EventDateRange.types' + +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 open = (next: EventTimeField) => { + Keyboard.dismiss() + setField(next) + control.open() + } + + return ( + <> + + {(['startsAt', 'endsAt'] as const).map(key => ( + + {labels[key]} + open(key)} + style={[ + a.px_md, + a.py_sm, + a.rounded_sm, + a.border, + t.atoms.bg_contrast_50, + key === 'endsAt' && isEndInvalid + ? {borderColor: t.palette.negative_500} + : {borderColor: 'transparent'}, + ]}> + + {formatEventDraftDate(values[key], i18n.locale)} + + + + ))} + + + + + + + {(['startsAt', 'endsAt'] as const).map(key => ( + + ))} + + + 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..de1a42a68 --- /dev/null +++ b/src/view/com/composer/event/EventDateRange.web.tsx @@ -0,0 +1,54 @@ +import {View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {atoms as a, useTheme} from '#/alf' +import * as TextField from '#/components/forms/TextField' +import { + fromLocalInputValue, + toLocalInputValue, +} from '#/features/events/draft' +import {type EventDateRangeProps} from './EventDateRange.types' + +export function EventDateRange({ + startsAt, + endsAt, + isEndInvalid, + onChange, +}: EventDateRangeProps) { + const t = useTheme() + const {t: l} = useLingui() + const values = {startsAt, endsAt} + const labels = {startsAt: l`Start date`, endsAt: l`End date`} + + return ( + + {(['startsAt', 'endsAt'] as const).map(key => ( + + {labels[key]} + + { + const iso = fromLocalInputValue(e.target.value) + if (iso) onChange(key, iso) + }} + style={{ + flex: 1, + padding: '10px 14px', + font: 'inherit', + fontSize: a.text_md.fontSize, + color: t.atoms.text.color, + colorScheme: t.scheme, + background: 'transparent', + border: 0, + }} + /> + + + ))} + + ) +} diff --git a/src/view/com/composer/event/EventEditor.tsx b/src/view/com/composer/event/EventEditor.tsx index 0f6b56af3..2e327f0f9 100644 --- a/src/view/com/composer/event/EventEditor.tsx +++ b/src/view/com/composer/event/EventEditor.tsx @@ -2,6 +2,7 @@ import {View} from 'react-native' import {Trans, useLingui} from '@lingui/react/macro' import {countGraphemes} from 'unicode-segmenter/grapheme' +import {EventDateRange} from '#/view/com/composer/event/EventDateRange' import {type PostAction} from '#/view/com/composer/state/composer' import {atoms as a, useTheme} from '#/alf' import {Button, ButtonText} from '#/components/Button' @@ -11,6 +12,7 @@ import {Text} from '#/components/Typography' import {useAnalytics} from '#/analytics' import { areEventDetailsValid, + changeEventTime, EVENT_DESCRIPTION_MAX_GRAPHEMES, EVENT_NAME_MAX_GRAPHEMES, type EventDraft, @@ -218,14 +220,9 @@ function WhenStep({ update: (fields: Partial) => void }) { const t = useTheme() - const {t: l, i18n} = useLingui() + const {t: l} = useLingui() const endsBeforeStart = eventEndsBeforeStart(event) const startsInPast = eventStartsInPast(event) - const formatDate = (iso: string) => - new Intl.DateTimeFormat(i18n.locale, { - dateStyle: 'medium', - timeStyle: 'short', - }).format(new Date(iso)) return ( @@ -243,24 +240,12 @@ function WhenStep({ /> - - - - Start date - - - {formatDate(event.startsAt)} - - - - - End date - - - {formatDate(event.endsAt)} - - - + update(changeEventTime(event, field, iso))} + /> {endsBeforeStart ? ( ({ 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')} + /> + ), + } +}) + import {EventEditor} from '../EventEditor' function composerWithEvent(): ComposerState { @@ -212,4 +231,15 @@ describe('EventEditor', () => { 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') + }) }) -- knotmirror 0.0.1