diff --git a/__tests__/lib/string.test.ts b/__tests__/lib/string.test.ts index add231cea..78694b077 100644 --- a/__tests__/lib/string.test.ts +++ b/__tests__/lib/string.test.ts @@ -13,7 +13,7 @@ import {cleanError} from '../../src/lib/strings/errors' import {createFullHandle, makeValidHandle} from '../../src/lib/strings/handles' import {enforceLen} from '../../src/lib/strings/helpers' import {detectLinkables} from '../../src/lib/strings/rich-text-detection' -import {shortenLinks} from '../../src/lib/strings/rich-text-manip' +import {expandLinks, shortenLinks} from '../../src/lib/strings/rich-text-manip' import { makeRecordUri, toNiceDomain, @@ -287,6 +287,40 @@ describe('toShareUrl', () => { }) }) +describe('expandLinks', () => { + const inputs = [ + 'start https://middle.com/foo/bar?baz=bux#hash end', + 'https://start.com/looooooooooooooooooooooooooooooooooooooooooooooooooong/path middle https://end.com/foo/bar', + 'no links here', + 'a short one https://example.com/x stays as it is', + ] + + it.each(inputs)('restores the full links of %s', input => { + const typed = new RichText({text: input}) + typed.detectFacetsWithoutResolution() + const published = shortenLinks(typed) + + const restored = expandLinks(published) + + expect(restored.text).toBe(input) + expect(restored.facets).toStrictEqual(typed.facets) + }) + + it('leaves the published text as it was', () => { + const typed = new RichText({ + text: 'see https://example.com/looooooooooooooooooooooooooooooong/path', + }) + typed.detectFacetsWithoutResolution() + const published = shortenLinks(typed) + const before = published.text + + expandLinks(published) + + expect(published.text).toBe(before) + expect(before).not.toBe(typed.text) + }) +}) + describe('shortenLinks', () => { const inputs = [ 'start https://middle.com/foo/bar?baz=bux#hash end', @@ -904,6 +938,111 @@ describe('parseEmbedPlayerFromUrl', () => { expect(res).toEqual(output) } }) + + describe('assembly conversations', () => { + const PRODUCTION = 'https://assembly.blacksky.community' + + function parserFor(assemblyUrl: string) { + let parse = parseEmbedPlayerFromUrl + jest.isolateModules(() => { + jest.doMock('#/env', () => ({ + ...jest.requireActual>('#/env'), + ASSEMBLY_URL: assemblyUrl, + })) + parse = jest.requireActual<{ + parseEmbedPlayerFromUrl: typeof parseEmbedPlayerFromUrl + }>('#/lib/strings/embed-player').parseEmbedPlayerFromUrl + }) + jest.dontMock('#/env') + return parse + } + + function conversation(playerUri: string) { + return { + type: 'assembly_conversation', + source: 'assembly', + playerUri, + hideDetails: false, + } + } + + it('accepts the production host', () => { + const parse = parserFor(PRODUCTION) + + expect(parse(`${PRODUCTION}/2demo`)).toEqual( + conversation(`${PRODUCTION}/2demo`), + ) + expect(parse(`${PRODUCTION}/2demo?utm_source=post`)).toEqual( + conversation(`${PRODUCTION}/2demo`), + ) + expect(parse('http://assembly.blacksky.community/2demo')).toEqual( + conversation(`${PRODUCTION}/2demo`), + ) + }) + + it('accepts only the production host by default', () => { + const parse = parserFor(PRODUCTION) + + expect(parse('http://localhost:5000/2demo')).toBeUndefined() + expect(parse('https://example.com/2demo')).toBeUndefined() + expect( + parse('https://assembly.blacksky.community.example.com/2demo'), + ).toBeUndefined() + }) + + it('accepts the configured host', () => { + const parse = parserFor('http://localhost:5000') + + expect(parse('http://localhost:5000/2demo')).toEqual( + conversation('http://localhost:5000/2demo'), + ) + expect(parse(`${PRODUCTION}/2demo`)).toEqual( + conversation(`${PRODUCTION}/2demo`), + ) + }) + + it('accepts a configured host written with a trailing slash', () => { + const parse = parserFor('http://localhost:5000/') + + expect(parse('http://localhost:5000/2demo')).toEqual( + conversation('http://localhost:5000/2demo'), + ) + }) + + it('rejects another port of the configured host', () => { + const parse = parserFor('http://localhost:5000') + + expect(parse('http://localhost:8081/2demo')).toBeUndefined() + expect(parse('http://localhost/2demo')).toBeUndefined() + }) + + it.each([PRODUCTION, 'http://localhost:5000'])( + 'rejects nested paths and short ids on %s', + origin => { + const parse = parserFor('http://localhost:5000') + + expect(parse(`${origin}/report/r7demo`)).toBeUndefined() + expect(parse(`${origin}/2demo/extra`)).toBeUndefined() + expect(parse(`${origin}/2demo/`)).toBeUndefined() + expect(parse(`${origin}/2dem`)).toBeUndefined() + expect(parse(`${origin}/`)).toBeUndefined() + expect(parse(origin)).toBeUndefined() + }, + ) + + it.each(['', 'not a url', 'file:///srv'])( + 'keeps the production host when configured with "%s"', + assemblyUrl => { + const parse = parserFor(assemblyUrl) + + expect(parse(`${PRODUCTION}/2demo`)).toEqual( + conversation(`${PRODUCTION}/2demo`), + ) + expect(parse('http://localhost:5000/2demo')).toBeUndefined() + expect(parse('file:///2demo')).toBeUndefined() + }, + ) + }) }) describe('createStarterPackLinkFromAndroidReferrer', () => { diff --git a/package.json b/package.json index 4d119ddef..686d0603d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.130.3", + "version": "1.131.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/analytics/features/types.ts b/src/analytics/features/types.ts index d84cc8f0f..6bdb06d0f 100644 --- a/src/analytics/features/types.ts +++ b/src/analytics/features/types.ts @@ -18,6 +18,7 @@ export enum Features { AppviewFallbackThresholds = 'appview_fallback:thresholds', SearchAppviewRoute = 'search_appview:route', StreamplaceWatchEnable = 'streamplace:watch:enable', + PollsEnable = 'polls:enable', AATest = 'aa-test', } diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 10d611d96..b602466ea 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -333,6 +333,9 @@ export type Events = { 'composer:gif:open': {} 'composer:gif:select': {} + 'composer:poll:open': {} + 'composer:poll:remove': {} + 'composer:poll:statementAdd': {count: number} 'composer:image:edit': { platform: Platform['OS'] } @@ -410,6 +413,8 @@ export type Events = { isPartOfThread: boolean hasLink: boolean hasQuote: boolean + hasPoll: boolean + pollStatementCount: number langs: string logContext: 'Composer' } @@ -1170,6 +1175,23 @@ export type Events = { 'share:press:recentDm': {} 'share:press:embed': {} + 'assembly:create': { + conversationId: string + statementCount: number + isReplay: boolean + } + 'assembly:create:error': { + stage: 'record' | 'token' | 'create' + code: string + } + 'assembly:vote': { + conversationId: string + tid: number + value: 'agree' | 'disagree' | 'pass' + remaining: number + } + 'assembly:complete': {conversationId: string} + 'embed:standardSite:view': {url: string} 'embed:standardSite:article:press': {url: string} 'embed:standardSite:article:longPress': {url: string} diff --git a/src/components/Post/Embed/ExternalEmbed/AssemblyEmbed.tsx b/src/components/Post/Embed/ExternalEmbed/AssemblyEmbed.tsx index 9091d7d6c..1b2cb8441 100644 --- a/src/components/Post/Embed/ExternalEmbed/AssemblyEmbed.tsx +++ b/src/components/Post/Embed/ExternalEmbed/AssemblyEmbed.tsx @@ -1,19 +1,38 @@ -import {useCallback, useEffect, useState} from 'react' -import {Image, Linking, Pressable, StyleSheet, View} from 'react-native' -import {type AppBskyEmbedExternal} from '@atproto/api' - +import {useCallback, useEffect, useRef, useState} from 'react' +import {Image, Pressable, StyleSheet, View} from 'react-native' +import { + type AppBskyEmbedExternal, + type AppBskyRichtextFacet, + RichText, +} from '@atproto/api' +import {Trans, useLingui} from '@lingui/react/macro' + +import {assemblyReportUrl, assemblyUrl} from '#/lib/api/assembly' +import {pollTopicFromText, type PollVoteValue} from '#/lib/api/poll' +import {useOpenLink} from '#/lib/hooks/useOpenLink' import {type EmbedPlayerParams} from '#/lib/strings/embed-player' +import {expandLinks} from '#/lib/strings/rich-text-manip' import {useAgent, useSession} from '#/state/session' import {Logo as BlackskyLogo} from '#/view/icons/Logo' import {atoms as a, useTheme} from '#/alf' import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' +import {ASSEMBLY_URL} from '#/env' +import {VoteButtons} from './VoteButtons' + +const ASSEMBLY_API = `${ASSEMBLY_URL.replace(/\/+$/, '')}/api/v3` -const ASSEMBLY_API = 'https://assembly.blacksky.community/api/v3' +const VOTE_NUMBERS: Record = { + agree: -1, + disagree: 1, + pass: 0, +} interface Statement { tid: number txt: string remaining?: number + is_seed?: boolean author_name?: string author_avatar?: string author_is_blacksky_member?: boolean @@ -37,6 +56,7 @@ interface ConversationMeta { interface EmbedConversationResponse { conversation: ConversationMeta nextComment: Statement | null + report_id?: string | null } interface ParticipationInitResponse { @@ -49,6 +69,19 @@ interface VoteResponse { nextComment?: Statement } +function repeatsTopic( + topic: string, + text: string | undefined, + facets: AppBskyRichtextFacet.Main[] | undefined, +): boolean { + if (!text) return false + if (pollTopicFromText(text) === topic) return true + if (!facets?.length) return false + return ( + pollTopicFromText(expandLinks(new RichText({text, facets})).text) === topic + ) +} + function extractConversationId(uri: string): string { try { const url = new URL(uri) @@ -60,14 +93,22 @@ function extractConversationId(uri: string): string { export function AssemblyEmbed({ link, + postText, + postFacets, }: { link: AppBskyEmbedExternal.ViewExternal params: EmbedPlayerParams + postText?: string + postFacets?: AppBskyRichtextFacet.Main[] }) { const t = useTheme() + const {t: l} = useLingui() + const ax = useAnalytics() const agent = useAgent() + const openLink = useOpenLink() const {currentAccount} = useSession() const conversationId = extractConversationId(link.uri) + const hasCompleted = useRef(false) const [data, setData] = useState(null) const [statement, setStatement] = useState(null) @@ -75,21 +116,28 @@ export function AssemblyEmbed({ const [error, setError] = useState(null) const [allVoted, setAllVoted] = useState(false) const [notFound, setNotFound] = useState(false) - const [participationToken, setParticipationToken] = useState( - null, - ) - - const isAuthenticated = !!currentAccount?.did + const [participation, setParticipation] = useState<{ + did: string + token: string + } | null>(null) + + const viewerDid = currentAccount?.did + const isAuthenticated = !!viewerDid + const participationToken = + participation && participation.did === viewerDid + ? participation.token + : null useEffect(() => { if (!conversationId) return + let cancelled = false const init = async () => { - // 1. Fetch conversation data (public endpoint, CORS-safe) try { const convResp = await fetch( `${ASSEMBLY_API}/embed/conversation?conversation_id=${conversationId}`, ) + if (cancelled) return if (!convResp.ok) { if (convResp.status === 400 || convResp.status === 404) { setNotFound(true) @@ -97,22 +145,22 @@ export function AssemblyEmbed({ return } const convData = (await convResp.json()) as EmbedConversationResponse + if (cancelled) return setData(convData) setStatement(convData.nextComment) - if (!convData.nextComment) setAllVoted(true) + setAllVoted(!convData.nextComment) if (!convData.conversation.is_active) return } catch { - setError('Failed to load conversation') + if (!cancelled) setError('Failed to load conversation') return } - // 2. If authenticated, try to get a participation JWT (separate try/catch — non-fatal) - if (isAuthenticated && currentAccount?.did) { + if (viewerDid) { try { const xidParams = new URLSearchParams({ conversation_id: conversationId, includePCA: 'false', - xid: currentAccount.did, + xid: viewerDid, }) const initResp = await fetch( @@ -122,40 +170,39 @@ export function AssemblyEmbed({ if (initResp.ok) { const initData = (await initResp.json()) as ParticipationInitResponse + if (cancelled) return if (initData.auth?.token) { - setParticipationToken(initData.auth.token) + setParticipation({did: viewerDid, token: initData.auth.token}) } - // Use personalized next comment (excludes already-voted) if (initData.nextComment) { setStatement(initData.nextComment) } else { - // User has voted on all statements setStatement(null) setAllVoted(true) } } - } catch { - // participationInit failed (likely CORS) — continue with public data - } + } catch {} } } void init() - }, [conversationId, isAuthenticated, currentAccount?.did]) + return () => { + cancelled = true + } + }, [conversationId, viewerDid]) const handleVote = useCallback( - async (value: -1 | 0 | 1) => { + async (value: PollVoteValue) => { if (!statement || voting) return setVoting(true) setError(null) try { + const vote = VOTE_NUMBERS[value] let voteAtUri: string | undefined - // If authenticated and statement has an AT URI, create a signed vote - // record in the user's repo as proof of identity. if (agent.session && statement.at_uri && statement.at_cid) { const createResult = await agent.com.atproto.repo.createRecord({ repo: agent.assertDid, @@ -166,16 +213,13 @@ export function AssemblyEmbed({ uri: statement.at_uri, cid: statement.at_cid, }, - value, + value: vote, createdAt: new Date().toISOString(), }, }) voteAtUri = createResult.data.uri } - // Submit to assembly's verified vote endpoint. - // If authenticated: server fetches the record from user's PDS to verify. - // If anonymous: server accepts the vote directly (conversation allows it). const voteHeaders: Record = { 'Content-Type': 'application/json', } @@ -188,7 +232,7 @@ export function AssemblyEmbed({ body: JSON.stringify({ conversation_id: conversationId, tid: statement.tid, - vote: value, + vote, ...(voteAtUri ? {vote_at_uri: voteAtUri} : {}), }), }) @@ -205,11 +249,22 @@ export function AssemblyEmbed({ const voteResult = (await voteResp.json()) as VoteResponse + ax.metric('assembly:vote', { + conversationId, + tid: statement.tid, + value, + remaining: voteResult.nextComment?.remaining ?? 0, + }) + if (voteResult.nextComment) { setStatement(voteResult.nextComment) } else { setAllVoted(true) setStatement(null) + if (!hasCompleted.current) { + hasCompleted.current = true + ax.metric('assembly:complete', {conversationId}) + } } } catch { setError('Vote failed. Please try again.') @@ -217,21 +272,24 @@ export function AssemblyEmbed({ setVoting(false) } }, - [agent, statement, conversationId, voting], + [agent, ax, statement, conversationId, voting, participationToken], ) const onVote = useCallback( - (value: -1 | 0 | 1) => { + (value: PollVoteValue) => { void handleVote(value) }, [handleVote], ) const openAssembly = useCallback(() => { - void Linking.openURL( - `https://assembly.blacksky.community/${conversationId}`, - ) - }, [conversationId]) + openLink(assemblyUrl(conversationId)) + }, [openLink, conversationId]) + + const reportId = data?.report_id + const openResults = useCallback(() => { + if (reportId) openLink(assemblyReportUrl(reportId)) + }, [openLink, reportId]) if (notFound) { return ( @@ -285,6 +343,16 @@ export function AssemblyEmbed({ ) } + const topic = repeatsTopic(data.conversation.topic, postText, postFacets) + ? undefined + : data.conversation.topic + const footer = ( + + ) + if (!data.conversation.is_active) { return ( This conversation is closed. - + {footer} ) } @@ -316,20 +384,20 @@ export function AssemblyEmbed({ {backgroundColor: t.atoms.bg_contrast_25.backgroundColor}, ]}> + accessibilityLabel={l`Sign in to vote`} + accessibilityHint={l`Opens the assembly page to sign in and vote`}> - Sign in to vote + Sign in to vote - + {footer} ) } @@ -341,7 +409,7 @@ export function AssemblyEmbed({ {backgroundColor: t.atoms.bg_contrast_25.backgroundColor}, ]}> @@ -356,62 +424,74 @@ export function AssemblyEmbed({ <> - - {statement.author_avatar ? ( - - ) : ( - - )} - - - {statement.author_name || 'Anonymous'} wrote: - - {(statement.author_is_team || - statement.author_is_blacksky_member || - statement.author_is_funder || - statement.author_is_oss_supporter) && ( - - {statement.author_is_team && ( - - - Admin - - - )} - {statement.author_is_blacksky_member && ( - - - Member - - - )} - {statement.author_is_funder && ( - - - Funder - - - )} - {statement.author_is_oss_supporter && ( - - - OSS - - - )} - + {!statement.is_seed && ( + + {statement.author_avatar ? ( + + ) : ( + )} + + + {statement.author_name || 'Anonymous'} wrote: + + {(statement.author_is_team || + statement.author_is_blacksky_member || + statement.author_is_funder || + statement.author_is_oss_supporter) && ( + + {statement.author_is_team && ( + + + Admin + + + )} + {statement.author_is_blacksky_member && ( + + + Member + + + )} + {statement.author_is_funder && ( + + + Funder + + + )} + {statement.author_is_oss_supporter && ( + + + OSS + + + )} + + )} + - + )} - [ - styles.voteButton, - { - borderColor: '#61C554', - backgroundColor: hovered - ? 'rgba(97, 197, 84, 0.15)' - : t.atoms.bg_contrast_25.backgroundColor, - }, - ]} - onPress={() => onVote(-1)} - disabled={voting} - accessibilityRole="button" - accessibilityLabel="Agree" - accessibilityHint="Vote agree on this statement"> - - {voting ? '...' : 'Agree'} - - - [ - styles.voteButton, - { - borderColor: '#F40B42', - backgroundColor: hovered - ? 'rgba(244, 11, 66, 0.12)' - : t.atoms.bg_contrast_25.backgroundColor, - }, - ]} - onPress={() => onVote(1)} - disabled={voting} - accessibilityRole="button" - accessibilityLabel="Disagree" - accessibilityHint="Vote disagree on this statement"> - - {voting ? '...' : 'Disagree'} - - - [ - styles.voteButton, - { - borderColor: t.atoms.border_contrast_low.borderColor, - backgroundColor: hovered - ? t.atoms.bg_contrast_50.backgroundColor - : t.atoms.bg_contrast_25.backgroundColor, - }, - ]} - onPress={() => onVote(0)} + - - {voting ? '...' : 'Pass / Unsure'} - - + passLabel={l`Pass / Unsure`} + onVote={onVote} + /> {error ? ( @@ -516,7 +540,7 @@ export function AssemblyEmbed({ ) : null} - + {footer} ) } @@ -525,7 +549,7 @@ function AssemblyHeader({ topic, description, }: { - topic: string + topic?: string description?: string }) { const t = useTheme() @@ -538,11 +562,13 @@ function AssemblyHeader({ People's Assembly - - {topic} - + {topic ? ( + + {topic} + + ) : null} {description ? ( void}) { +function AssemblyFooter({ + onPress, + onPressResults, +}: { + onPress: () => void + onPressResults?: () => void +}) { + const {t: l} = useLingui() return ( + {onPressResults ? ( + + + See results + + + ) : null} + accessibilityLabel={l`Submit a statement`} + accessibilityHint={l`Opens the assembly conversation page`}> - Submit a statement → + Submit a statement → @@ -627,17 +671,8 @@ const styles = StyleSheet.create({ zIndex: 1, }, voteButtons: { - flexDirection: 'row', - gap: 8, marginTop: 10, }, - voteButton: { - flex: 1, - paddingVertical: 10, - borderRadius: 8, - borderWidth: 2, - alignItems: 'center', - }, statementAuthorRow: { flexDirection: 'row', alignItems: 'center', @@ -672,6 +707,9 @@ const styles = StyleSheet.create({ }, footer: { marginTop: 10, - alignItems: 'flex-end', + flexDirection: 'row', + flexWrap: 'wrap', + justifyContent: 'flex-end', + gap: 12, }, }) diff --git a/src/components/Post/Embed/ExternalEmbed/VoteButtons.tsx b/src/components/Post/Embed/ExternalEmbed/VoteButtons.tsx new file mode 100644 index 000000000..c1482b32b --- /dev/null +++ b/src/components/Post/Embed/ExternalEmbed/VoteButtons.tsx @@ -0,0 +1,101 @@ +import {Pressable, StyleSheet, View} from 'react-native' +import {useLingui} from '@lingui/react/macro' + +import {type PollVoteValue} from '#/lib/api/poll' +import {atoms as a, useTheme} from '#/alf' +import {Text} from '#/components/Typography' + +const AGREE = '#61C554' +const DISAGREE = '#F40B42' + +export function VoteButtons({ + onVote, + disabled, + pending, + passLabel, +}: { + onVote: (value: PollVoteValue) => void + disabled?: boolean + pending?: boolean + passLabel?: string +}) { + const t = useTheme() + const {t: l} = useLingui() + const idle = t.atoms.bg_contrast_25.backgroundColor + const passColor = t.atoms.text_contrast_medium.color + + const options: { + value: PollVoteValue + label: string + hint: string + color: string + border: string + hover: string + }[] = [ + { + value: 'agree', + label: l`Agree`, + hint: l`Vote agree on this statement`, + color: AGREE, + border: AGREE, + hover: 'rgba(97, 197, 84, 0.15)', + }, + { + value: 'disagree', + label: l`Disagree`, + hint: l`Vote disagree on this statement`, + color: DISAGREE, + border: DISAGREE, + hover: 'rgba(244, 11, 66, 0.12)', + }, + { + value: 'pass', + label: passLabel ?? l`Pass`, + hint: l`Pass on this statement`, + color: passColor, + border: t.atoms.border_contrast_low.borderColor, + hover: t.atoms.bg_contrast_50.backgroundColor, + }, + ] + + return ( + true}> + {options.map(option => ( + [ + styles.button, + { + borderColor: option.border, + backgroundColor: hovered ? option.hover : idle, + }, + ]} + onPress={() => onVote(option.value)} + disabled={disabled} + accessibilityRole="button" + accessibilityLabel={option.label} + accessibilityHint={option.hint} + accessibilityState={{disabled: !!disabled}}> + + {pending ? '...' : option.label} + + + ))} + + ) +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + gap: 8, + }, + button: { + flex: 1, + paddingVertical: 10, + borderRadius: 8, + borderWidth: 2, + alignItems: 'center', + }, +}) diff --git a/src/components/Post/Embed/ExternalEmbed/__tests__/AssemblyEmbed.test.tsx b/src/components/Post/Embed/ExternalEmbed/__tests__/AssemblyEmbed.test.tsx new file mode 100644 index 000000000..0eb4b1d39 --- /dev/null +++ b/src/components/Post/Embed/ExternalEmbed/__tests__/AssemblyEmbed.test.tsx @@ -0,0 +1,943 @@ +import {type ReactNode} from 'react' +import {type AppBskyFeedDefs, RichText} from '@atproto/api' +import {i18n} from '@lingui/core' +import {I18nProvider} from '@lingui/react' +import { + act, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react-native' + +jest.mock('#/env', () => ({ + ...jest.requireActual>('#/env'), + ASSEMBLY_URL: 'http://localhost:5000/', +})) +jest.mock('#/alf', () => { + const blank = new Proxy({}, {get: () => ({})}) + return {atoms: blank, useTheme: () => ({atoms: blank})} +}) +jest.mock('#/components/Typography', () => { + const {Text} = require('react-native') + return {Text} +}) +jest.mock('#/view/icons/Logo', () => ({Logo: () => null})) + +type Viewer = {did: string} | undefined +let mockViewer: Viewer +const mockCreateRecord = jest.fn() +const mockAgent = { + get session() { + return mockViewer + }, + get assertDid() { + return mockViewer?.did + }, + com: {atproto: {repo: {createRecord: mockCreateRecord}}}, +} +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, + useSession: () => ({currentAccount: mockViewer}), +})) + +const mockOpenLink = jest.fn() +jest.mock('#/lib/hooks/useOpenLink', () => ({ + useOpenLink: () => mockOpenLink, +})) + +const mockMetric = jest.fn() +const mockAnalytics = {metric: mockMetric} +jest.mock('#/analytics', () => ({ + useAnalytics: () => mockAnalytics, +})) + +jest.mock('#/lib/haptics', () => ({useHaptics: () => jest.fn()})) +jest.mock('#/lib/sharing', () => ({shareUrl: jest.fn()})) +jest.mock('#/state/preferences', () => ({ + useExternalEmbedsPrefs: () => undefined, +})) +jest.mock('#/components/Divider', () => ({Divider: () => null})) +jest.mock('#/components/icons/Globe', () => ({ + Earth_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/Link', () => ({Link: () => null})) +jest.mock('../ExternalGif', () => ({ExternalGif: () => null})) +jest.mock('../ExternalPlayer', () => ({ExternalPlayer: () => null})) +jest.mock('../Gif', () => ({GifEmbed: () => null})) +jest.mock('#/components/moderation/ContentHider', () => ({ + ContentHider: ({children}: {children: ReactNode}) => children, +})) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => undefined, +})) +jest.mock('#/state/queries/embed-fallback', () => ({ + useEmbedFallback: () => ({}), +})) +jest.mock('#/state/queries/profile', () => ({ + unstableCacheProfileView: jest.fn(), +})) +jest.mock('#/view/com/util/Link', () => ({Link: () => null})) +jest.mock('#/view/com/util/PostMeta', () => ({PostMeta: () => null})) +jest.mock('#/components/images/Gallery', () => ({GalleryBleed: () => null})) +jest.mock('#/components/moderation/PostAlerts', () => ({ + PostAlerts: () => null, +})) +jest.mock('#/components/RichText', () => ({RichText: () => null})) +jest.mock('#/components/StarterPack/StarterPackCard', () => ({ + Embed: () => null, +})) +jest.mock('#/components/SubtleHover', () => ({SubtleHover: () => null})) +jest.mock('#/components/Post/Embed/StandardSiteEmbed', () => ({ + StandardSiteEmbed: () => null, +})) +jest.mock('#/components/Post/Embed/ChatInviteEmbed', () => ({ + ChatInviteEmbed: () => null, +})) +jest.mock('#/components/Post/Embed/FeedEmbed', () => ({ + ModeratedFeedEmbed: () => null, +})) +jest.mock('#/components/Post/Embed/ImageEmbed', () => ({ + ImageEmbed: () => null, +})) +jest.mock('#/components/Post/Embed/ListEmbed', () => ({ + ModeratedListEmbed: () => null, +})) +jest.mock('#/components/Post/Embed/PostPlaceholder', () => ({ + PostPlaceholder: () => null, +})) +jest.mock('#/components/Post/Embed/VideoEmbed', () => ({ + VideoEmbed: () => null, +})) + +import {pollTopicFromText} from '#/lib/api/poll' +import {type EmbedPlayerParams} from '#/lib/strings/embed-player' +import {shortenLinks} from '#/lib/strings/rich-text-manip' +import {Embed} from '#/components/Post/Embed' +import {ExternalEmbed} from '#/components/Post/Embed/ExternalEmbed' +import {AssemblyEmbed} from '../AssemblyEmbed' + +const NOW = '2026-09-27T12:00:00.000Z' +const ORIGIN = 'http://localhost:5000' +const API = `${ORIGIN}/api/v3` +const VOTE_URL = `${API}/embed/vote` +const CONVERSATION_ID = '2demo' +const PAGE_URL = `${ORIGIN}/${CONVERSATION_ID}` +const TOPIC = 'Should the garden stay open late?' +const VIEWER = 'did:plc:viewer' + +const LINK = {uri: PAGE_URL, title: TOPIC, description: '1. Yes, until sunset'} +const PARAMS: EmbedPlayerParams = { + type: 'assembly_conversation', + source: 'assembly', + playerUri: PAGE_URL, + hideDetails: false, +} + +const SEED = {tid: 0, txt: 'Yes, until sunset', remaining: 2, is_seed: true} +const SECOND_SEED = { + tid: 1, + txt: 'Only on weekends', + remaining: 1, + is_seed: true, +} +const PARTICIPANT = { + tid: 7, + txt: 'Add more lights first', + remaining: 1, + is_seed: false, + author_name: 'Ada', +} + +type Json = Record + +function conversation(overrides: Json = {}, meta: Json = {}): Json { + return { + conversation: { + conversation_id: CONVERSATION_ID, + topic: TOPIC, + is_active: true, + auth_needed_to_vote: false, + ...meta, + }, + nextComment: SEED, + ...overrides, + } +} + +function reply(body: Json, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: () => Promise.resolve(body), + text: () => Promise.resolve(JSON.stringify(body)), + } as Response +} + +const fetchMock = jest.fn, Parameters>() + +function serve({ + conversation: conversationReply = reply(conversation()), + participation = reply({}), + votes = [], +}: { + conversation?: Response + participation?: Response + votes?: Response[] +}) { + const pending = [...votes] + fetchMock.mockImplementation((input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : '' + if (url.startsWith(`${API}/embed/conversation?`)) { + return Promise.resolve(conversationReply) + } + if (url.startsWith(`${API}/participationInit?`)) { + return Promise.resolve(participation) + } + const vote = url === VOTE_URL ? pending.shift() : undefined + if (vote) return Promise.resolve(vote) + return Promise.reject(new Error(`Unexpected request to ${url}`)) + }) +} + +function requests() { + return fetchMock.mock.calls.map(([input]) => input) +} + +function voteRequests() { + return fetchMock.mock.calls + .filter(([input]) => input === VOTE_URL) + .map(([, init]) => init) +} + +function renderCard(props: {postText?: string} = {}) { + return render( + + + , + ) +} + +function metricsNamed(name: string) { + return mockMetric.mock.calls.filter(([event]) => event === name) +} + +beforeEach(() => { + jest.useFakeTimers({ + now: new Date(NOW), + doNotFake: [ + 'hrtime', + 'nextTick', + 'performance', + 'queueMicrotask', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'requestIdleCallback', + 'cancelIdleCallback', + 'setImmediate', + 'clearImmediate', + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout', + ], + }) + jest.clearAllMocks() + fetchMock.mockReset() + global.fetch = fetchMock + mockViewer = undefined +}) + +afterEach(() => { + jest.useRealTimers() +}) + +describe('AssemblyEmbed', () => { + it('reads the conversation from the configured server', async () => { + serve({}) + renderCard() + + await screen.findByText(SEED.txt) + + expect(requests()).toEqual([ + `${API}/embed/conversation?conversation_id=${CONVERSATION_ID}`, + ]) + }) + + describe('author row', () => { + it('is hidden for a seed statement', async () => { + serve({}) + renderCard() + + await screen.findByText(SEED.txt) + + expect(screen.queryByText('Anonymous wrote:')).toBeNull() + expect(screen.queryByText(/wrote:/)).toBeNull() + }) + + it('is hidden for a seed statement that names its author', async () => { + serve({ + conversation: reply( + conversation({ + nextComment: { + ...SEED, + author_name: 'Ada', + author_is_blacksky_member: true, + }, + }), + ), + }) + renderCard() + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(/wrote:/)).toBeNull() + expect(screen.queryByText('Member')).toBeNull() + }) + + it('is shown for a participant statement', async () => { + serve({ + conversation: reply( + conversation({ + nextComment: {...PARTICIPANT, author_is_blacksky_member: true}, + }), + ), + }) + renderCard() + + await screen.findByText(PARTICIPANT.txt) + + expect(screen.getByText('Ada wrote:')).toBeTruthy() + expect(screen.getByText('Member')).toBeTruthy() + }) + + it('is shown for a statement that does not say whether it is a seed', async () => { + serve({ + conversation: reply( + conversation({nextComment: {tid: 3, txt: 'Close at nine'}}), + ), + }) + renderCard() + + await screen.findByText('Close at nine') + + expect(screen.getByText('Anonymous wrote:')).toBeTruthy() + }) + }) + + describe('topic', () => { + it('is shown when there is no post text', async () => { + serve({}) + renderCard() + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + it('is shown when the post text is empty', async () => { + serve({}) + renderCard({postText: ''}) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + it('is shown when the post text says something else', async () => { + serve({}) + renderCard({postText: `${TOPIC} Tell me what you think.`}) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + it('is hidden when it equals the post text', async () => { + serve({}) + renderCard({postText: TOPIC}) + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(TOPIC)).toBeNull() + }) + + it('is hidden when it equals the post text once whitespace is collapsed', async () => { + serve({}) + renderCard({postText: ' Should the garden\n\nstay open late?\n'}) + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(TOPIC)).toBeNull() + }) + + it('is hidden when it equals the shortened post text', async () => { + const shortened = `${'a'.repeat(199)}…` + serve({conversation: reply(conversation({}, {topic: shortened}))}) + renderCard({postText: 'a'.repeat(240)}) + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(shortened)).toBeNull() + }) + + it('is shown when only the start of a long post text matches', async () => { + const topic = 'a'.repeat(199) + serve({conversation: reply(conversation({}, {topic}))}) + renderCard({postText: 'a'.repeat(240)}) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(topic)).toBeTruthy() + }) + + it('is hidden on a closed conversation that repeats the post text', async () => { + serve({conversation: reply(conversation({}, {is_active: false}))}) + renderCard({postText: TOPIC}) + + await screen.findByText('This conversation is closed.') + + expect(screen.queryByText(TOPIC)).toBeNull() + }) + }) + + describe('links', () => { + it('offers the results only when the conversation has a report', async () => { + serve({conversation: reply(conversation({report_id: 'r7demo'}))}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByLabelText('See results')) + + expect(screen.getByText('See results')).toBeTruthy() + expect(mockOpenLink).toHaveBeenCalledTimes(1) + expect(mockOpenLink).toHaveBeenCalledWith(`${ORIGIN}/report/r7demo`) + }) + + it.each([ + {state: 'is missing', overrides: {}}, + {state: 'is null', overrides: {report_id: null}}, + {state: 'is empty', overrides: {report_id: ''}}, + ])('offers no results when the report $state', async ({overrides}) => { + serve({conversation: reply(conversation(overrides))}) + renderCard() + + await screen.findByText(SEED.txt) + + expect(screen.queryByText('See results')).toBeNull() + expect(screen.queryByLabelText('See results')).toBeNull() + expect(screen.getByLabelText('Submit a statement')).toBeTruthy() + }) + + it('offers the results of a closed conversation', async () => { + serve({ + conversation: reply( + conversation({report_id: 'r7demo'}, {is_active: false}), + ), + }) + renderCard() + + await screen.findByText('This conversation is closed.') + fireEvent.press(screen.getByLabelText('See results')) + + expect(mockOpenLink).toHaveBeenCalledTimes(1) + expect(mockOpenLink).toHaveBeenCalledWith(`${ORIGIN}/report/r7demo`) + }) + + it('opens the conversation page from the footer', async () => { + serve({conversation: reply(conversation({report_id: 'r7demo'}))}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByLabelText('Submit a statement')) + + expect(screen.getByText('Submit a statement →')).toBeTruthy() + expect(mockOpenLink).toHaveBeenCalledTimes(1) + expect(mockOpenLink).toHaveBeenCalledWith(PAGE_URL) + }) + + it('opens the conversation page to sign in', async () => { + serve({ + conversation: reply(conversation({}, {auth_needed_to_vote: true})), + }) + renderCard() + + fireEvent.press(await screen.findByLabelText('Sign in to vote')) + + expect(screen.getByText('Sign in to vote')).toBeTruthy() + expect(mockOpenLink).toHaveBeenCalledTimes(1) + expect(mockOpenLink).toHaveBeenCalledWith(PAGE_URL) + }) + }) + + describe('voting', () => { + it.each([ + ['agree', -1], + ['disagree', 1], + ['pass', 0], + ] as const)( + 'posts a vote to %s, shows the next statement and reports it', + async (value, vote) => { + serve({votes: [reply({nextComment: SECOND_SEED})]}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId(`pollVote-${value}`)) + await screen.findByText(SECOND_SEED.txt) + + expect(screen.queryByText(SEED.txt)).toBeNull() + expect(voteRequests()).toEqual([ + { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ + conversation_id: CONVERSATION_ID, + tid: SEED.tid, + vote, + }), + }, + ]) + expect(mockCreateRecord).not.toHaveBeenCalled() + expect(mockMetric.mock.calls).toEqual([ + [ + 'assembly:vote', + { + conversationId: CONVERSATION_ID, + tid: SEED.tid, + value, + remaining: SECOND_SEED.remaining, + }, + ], + ]) + }, + ) + + it('labels the pass button as unsure', async () => { + serve({}) + renderCard() + + await screen.findByText(SEED.txt) + + expect(screen.getByTestId('pollVote-pass')).toHaveProp( + 'accessibilityLabel', + 'Pass / Unsure', + ) + }) + + it('reports no remaining statements when the next one does not count them', async () => { + serve({votes: [reply({nextComment: {tid: 1, txt: 'Only on weekends'}})]}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText('Only on weekends') + + expect(mockMetric.mock.calls).toEqual([ + [ + 'assembly:vote', + { + conversationId: CONVERSATION_ID, + tid: SEED.tid, + value: 'agree', + remaining: 0, + }, + ], + ]) + }) + + it('signs the vote of a signed-in viewer', async () => { + mockViewer = {did: VIEWER} + const statement = { + ...PARTICIPANT, + at_uri: 'at://did:plc:ada/community.blacksky.assembly.statement/3kada', + at_cid: 'bafyreistatement', + } + const voteUri = `at://${VIEWER}/community.blacksky.assembly.vote/3kvote` + mockCreateRecord.mockResolvedValue({data: {uri: voteUri}}) + serve({ + participation: reply({ + auth: {token: 'participant-token'}, + nextComment: statement, + }), + votes: [reply({nextComment: SECOND_SEED})], + }) + renderCard() + + await screen.findByText(statement.txt) + fireEvent.press(screen.getByTestId('pollVote-disagree')) + await screen.findByText(SECOND_SEED.txt) + + expect(requests()).toEqual([ + `${API}/embed/conversation?conversation_id=${CONVERSATION_ID}`, + `${API}/participationInit?conversation_id=${CONVERSATION_ID}&includePCA=false&xid=did%3Aplc%3Aviewer`, + VOTE_URL, + ]) + expect(mockCreateRecord.mock.calls).toEqual([ + [ + { + repo: VIEWER, + collection: 'community.blacksky.assembly.vote', + record: { + $type: 'community.blacksky.assembly.vote', + subject: {uri: statement.at_uri, cid: statement.at_cid}, + value: 1, + createdAt: NOW, + }, + }, + ], + ]) + expect(voteRequests()).toEqual([ + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: 'Bearer participant-token', + }, + body: JSON.stringify({ + conversation_id: CONVERSATION_ID, + tid: statement.tid, + vote: 1, + vote_at_uri: voteUri, + }), + }, + ]) + expect(mockMetric.mock.calls).toEqual([ + [ + 'assembly:vote', + { + conversationId: CONVERSATION_ID, + tid: statement.tid, + value: 'disagree', + remaining: SECOND_SEED.remaining, + }, + ], + ]) + }) + + it('sends no token of a previous account after the account changes', async () => { + mockViewer = {did: VIEWER} + serve({participation: reply({auth: {token: 'first-account-token'}})}) + const view = renderCard() + await screen.findByText("You've voted on all statements.") + + mockViewer = {did: 'did:plc:second'} + serve({participation: reply({}, 500), votes: [reply({})]}) + view.rerender( + + + , + ) + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText("You've voted on all statements.") + + expect(requests().slice(2)).toEqual([ + `${API}/embed/conversation?conversation_id=${CONVERSATION_ID}`, + `${API}/participationInit?conversation_id=${CONVERSATION_ID}&includePCA=false&xid=did%3Aplc%3Asecond`, + VOTE_URL, + ]) + expect(voteRequests()).toEqual([ + { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ + conversation_id: CONVERSATION_ID, + tid: SEED.tid, + vote: -1, + }), + }, + ]) + }) + + it('ignores an answer for a previous account that arrives late', async () => { + mockViewer = {did: VIEWER} + let answerFirstAccount: (response: Response) => void = () => {} + const firstAccount = new Promise(resolve => { + answerFirstAccount = resolve + }) + fetchMock.mockImplementation((input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : '' + if (url.startsWith(`${API}/embed/conversation?`)) { + return Promise.resolve(reply(conversation())) + } + if (url.includes('xid=did%3Aplc%3Aviewer')) return firstAccount + if (url.startsWith(`${API}/participationInit?`)) { + return Promise.resolve(reply({}, 500)) + } + if (url === VOTE_URL) return Promise.resolve(reply({})) + return Promise.reject(new Error(`Unexpected request to ${url}`)) + }) + const view = renderCard() + await screen.findByText(SEED.txt) + + mockViewer = {did: 'did:plc:second'} + view.rerender( + + + , + ) + await waitFor(() => + expect(requests()).toContain( + `${API}/participationInit?conversation_id=${CONVERSATION_ID}&includePCA=false&xid=did%3Aplc%3Asecond`, + ), + ) + await act(async () => { + answerFirstAccount( + reply({ + auth: {token: 'first-account-token'}, + nextComment: PARTICIPANT, + }), + ) + await firstAccount + }) + + expect(screen.getByText(SEED.txt)).toBeTruthy() + expect(screen.queryByText(PARTICIPANT.txt)).toBeNull() + + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText("You've voted on all statements.") + + expect(voteRequests()).toEqual([ + { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ + conversation_id: CONVERSATION_ID, + tid: SEED.tid, + vote: -1, + }), + }, + ]) + }) + + it('reports nothing when the server refuses the vote', async () => { + serve({ + votes: [reply({error: 'polis_err_post_votes_social_needed'}, 403)], + }) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText('Sign in required to vote.') + + expect(screen.getByText(SEED.txt)).toBeTruthy() + expect(voteRequests()).toHaveLength(1) + expect(mockMetric).not.toHaveBeenCalled() + }) + + it('reports nothing when the vote does not reach the server', async () => { + serve({}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText('Vote failed. Please try again.') + + expect(screen.getByText(SEED.txt)).toBeTruthy() + expect(mockMetric).not.toHaveBeenCalled() + }) + }) + + describe('completion', () => { + it('is reported once after the last vote', async () => { + serve({votes: [reply({nextComment: SECOND_SEED}), reply({})]}) + renderCard() + + await screen.findByText(SEED.txt) + fireEvent.press(screen.getByTestId('pollVote-agree')) + await screen.findByText(SECOND_SEED.txt) + + expect(metricsNamed('assembly:complete')).toEqual([]) + + fireEvent.press(screen.getByTestId('pollVote-pass')) + await screen.findByText("You've voted on all statements.") + + expect(screen.queryByTestId('pollVote-pass')).toBeNull() + expect(mockMetric.mock.calls).toEqual([ + [ + 'assembly:vote', + { + conversationId: CONVERSATION_ID, + tid: SEED.tid, + value: 'agree', + remaining: SECOND_SEED.remaining, + }, + ], + [ + 'assembly:vote', + { + conversationId: CONVERSATION_ID, + tid: SECOND_SEED.tid, + value: 'pass', + remaining: 0, + }, + ], + ['assembly:complete', {conversationId: CONVERSATION_ID}], + ]) + }) + + it('is reported once when the last vote is sent twice', async () => { + serve({votes: [reply({}), reply({})]}) + renderCard() + + await screen.findByText(SEED.txt) + const agree = screen.getByTestId('pollVote-agree') + act(() => { + fireEvent.press(agree) + fireEvent.press(agree) + }) + await screen.findByText("You've voted on all statements.") + await waitFor(() => expect(voteRequests()).toHaveLength(2)) + await waitFor(() => expect(metricsNamed('assembly:vote')).toHaveLength(2)) + + expect(metricsNamed('assembly:complete')).toEqual([ + ['assembly:complete', {conversationId: CONVERSATION_ID}], + ]) + }) + + it('is not reported for a viewer who had already voted on everything', async () => { + serve({conversation: reply(conversation({nextComment: null}))}) + renderCard() + + await screen.findByText("You've voted on all statements.") + + expect(mockMetric).not.toHaveBeenCalled() + }) + }) +}) + +describe('post text reaching the card', () => { + it('hides the topic of a link card under a post that asks the same', async () => { + serve({}) + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(TOPIC)).toBeNull() + }) + + it('shows the topic of a link card without post text', async () => { + serve({}) + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + function post(text: string): AppBskyFeedDefs.PostView { + return { + $type: 'app.bsky.feed.defs#postView', + uri: 'at://did:plc:author/app.bsky.feed.post/3kpost', + cid: 'bafyreipost', + author: {did: 'did:plc:author', handle: 'author.test'}, + record: {$type: 'app.bsky.feed.post', text, createdAt: NOW}, + indexedAt: NOW, + } + } + + const embed = {$type: 'app.bsky.embed.external#view', external: LINK} + + it('hides the topic of an embed in a post that asks the same', async () => { + serve({}) + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.queryByText(TOPIC)).toBeNull() + }) + + it('hides the topic of an embed in a post whose link was shortened', async () => { + const typed = new RichText({ + text: 'Should we fund this? https://example.com/proposals/2026/garden-lights-and-benches', + }) + typed.detectFacetsWithoutResolution() + const published = shortenLinks(typed) + const topic = pollTopicFromText(typed.text) + serve({conversation: reply(conversation({}, {topic}))}) + const view: AppBskyFeedDefs.PostView = { + ...post(published.text), + record: { + $type: 'app.bsky.feed.post', + text: published.text, + facets: published.facets, + createdAt: NOW, + }, + } + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(published.text).not.toBe(typed.text) + expect(screen.queryByText(topic)).toBeNull() + }) + + it('shows the topic of an embed in a post that links somewhere else', async () => { + const typed = new RichText({ + text: 'Should we fund this? https://example.com/proposals/2026/garden-lights-and-benches', + }) + typed.detectFacetsWithoutResolution() + const published = shortenLinks(typed) + serve({}) + const view: AppBskyFeedDefs.PostView = { + ...post(published.text), + record: { + $type: 'app.bsky.feed.post', + text: published.text, + facets: published.facets, + createdAt: NOW, + }, + } + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + it('shows the topic of an embed in a post that says something else', async () => { + serve({}) + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) + + it('shows the topic of an embed that has no post', async () => { + serve({}) + render( + + + , + ) + + await screen.findByText(SEED.txt) + + expect(screen.getByText(TOPIC)).toBeTruthy() + }) +}) diff --git a/src/components/Post/Embed/ExternalEmbed/__tests__/VoteButtons.test.tsx b/src/components/Post/Embed/ExternalEmbed/__tests__/VoteButtons.test.tsx new file mode 100644 index 000000000..d233f0716 --- /dev/null +++ b/src/components/Post/Embed/ExternalEmbed/__tests__/VoteButtons.test.tsx @@ -0,0 +1,82 @@ +import {Pressable, Text} from 'react-native' +import {type I18n} from '@lingui/core' +import {render, userEvent} from '@testing-library/react-native' + +jest.mock('@lingui/react', () => { + const {i18n} = jest.requireActual<{i18n: I18n}>('@lingui/core') + i18n.loadAndActivate({locale: 'en', messages: {}}) + return { + useLingui: () => ({ + _: (descriptor: {id: string; message?: string}): string => + i18n._(descriptor), + }), + } +}) +jest.mock('#/alf', () => ({ + atoms: new Proxy({}, {get: () => ({})}), + useTheme: () => ({ + atoms: { + bg_contrast_25: {backgroundColor: '#F1F3F5'}, + bg_contrast_50: {backgroundColor: '#E2E7EC'}, + border_contrast_low: {borderColor: '#D4DBE2'}, + text_contrast_medium: {color: '#42576C'}, + text: {color: '#0B0F14'}, + }, + }), +})) +jest.mock('#/components/Typography', () => { + const {Text: RNText} = require('react-native') + return {Text: RNText} +}) + +import {VoteButtons} from '../VoteButtons' + +function renderInLink(buttons: React.ReactElement) { + const onLinkPress = jest.fn() + const view = render( + + Post text + {buttons} + , + ) + return {...view, onLinkPress} +} + +describe('VoteButtons', () => { + it('keeps a tap on a disabled button from reaching the enclosing link', async () => { + const onVote = jest.fn() + const {getByTestId, getByText, onLinkPress} = renderInLink( + , + ) + const user = userEvent.setup() + + await user.press(getByTestId('pollVote-agree')) + await user.press(getByTestId('pollVote-disagree')) + await user.press(getByTestId('pollVote-pass')) + + expect(onVote).not.toHaveBeenCalled() + expect(onLinkPress).not.toHaveBeenCalled() + + await user.press(getByText('Post text')) + + expect(onLinkPress).toHaveBeenCalledTimes(1) + }) + + it('casts the vote from an enabled button without reaching the enclosing link', async () => { + const onVote = jest.fn() + const {getByTestId, onLinkPress} = renderInLink( + , + ) + const user = userEvent.setup() + + await user.press(getByTestId('pollVote-disagree')) + + expect(onVote).toHaveBeenCalledTimes(1) + expect(onVote).toHaveBeenCalledWith('disagree') + expect(onLinkPress).not.toHaveBeenCalled() + }) +}) diff --git a/src/components/Post/Embed/ExternalEmbed/index.tsx b/src/components/Post/Embed/ExternalEmbed/index.tsx index 906eb5ad0..54578733f 100644 --- a/src/components/Post/Embed/ExternalEmbed/index.tsx +++ b/src/components/Post/Embed/ExternalEmbed/index.tsx @@ -1,7 +1,10 @@ import {useMemo} from 'react' import {type StyleProp, View, type ViewStyle} from 'react-native' import {Image} from 'expo-image' -import {type AppBskyEmbedExternal} from '@atproto/api' +import { + type AppBskyEmbedExternal, + type AppBskyRichtextFacet, +} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' @@ -33,11 +36,15 @@ export const ExternalEmbed = ({ onOpen, style, hideAlt, + postText, + postFacets, }: { link: AppBskyEmbedExternal.ViewExternal onOpen?: () => void style?: StyleProp hideAlt?: boolean + postText?: string + postFacets?: AppBskyRichtextFacet.Main[] }) => { const {_} = useLingui() const t = useTheme() @@ -102,7 +109,12 @@ export const ExternalEmbed = ({ if (embedPlayerParams?.type === 'assembly_conversation') { return ( - + ) } diff --git a/src/components/Post/Embed/index.tsx b/src/components/Post/Embed/index.tsx index 2fe377379..bee7e71d5 100644 --- a/src/components/Post/Embed/index.tsx +++ b/src/components/Post/Embed/index.tsx @@ -125,6 +125,13 @@ function MediaEmbed({ ) } + const record = rest.post?.record + const postRecord = bsky.dangerousIsType( + record, + AppBskyFeedPost.isRecord, + ) + ? record + : undefined return ( ) diff --git a/src/components/icons/Poll.tsx b/src/components/icons/Poll.tsx new file mode 100644 index 000000000..a74bc39f0 --- /dev/null +++ b/src/components/icons/Poll.tsx @@ -0,0 +1,7 @@ +import {createStrokeSVG} from './TEMPLATE' + +export const Poll_Stroke2_Corner0_Rounded = createStrokeSVG({ + paths: ['M4 20V10', 'M12 20V4', 'M20 20v-7'], + viewBox: '0 0 24 24', + strokeWidth: 2, +}) diff --git a/src/env/common.ts b/src/env/common.ts index 5a79e68eb..caf14e337 100644 --- a/src/env/common.ts +++ b/src/env/common.ts @@ -169,6 +169,12 @@ export const ACORN_SERVICE_URL: string = })() : 'http://localhost:3000') +export const ASSEMBLY_URL: string = + process.env.EXPO_PUBLIC_ASSEMBLY_URL || 'https://assembly.blacksky.community' +export const ASSEMBLY_SERVICE_DID: string = + process.env.EXPO_PUBLIC_ASSEMBLY_SERVICE_DID || + 'did:web:assembly.blacksky.community' + /** * Stripe publishable key for embedded checkout */ diff --git a/src/lib/api/__tests__/assembly-publish.test.ts b/src/lib/api/__tests__/assembly-publish.test.ts new file mode 100644 index 000000000..cc8bbe2f5 --- /dev/null +++ b/src/lib/api/__tests__/assembly-publish.test.ts @@ -0,0 +1,756 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {logger} from '#/logger' +import {fetchResolveLinkQuery} from '#/state/queries/resolve-link' +import {AssemblyError, ensureAssembly} from '../assembly' +import {admitFeedPost, fetchCommunityFeedTarget} from '../community-feed' +import {post, ReplyDeletedError, resolveEmbed} from '../index' +import {type AssemblyRef} from '../poll' +import {imageToThumb} from '../resolve' +import {postToSpace} from '../space-post' +import {uploadBlob} from '../upload-blob' + +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('#/env', () => ({ + ...jest.requireActual>('#/env'), + ASSEMBLY_URL: 'https://assembly.blacksky.community', +})) +jest.mock('../assembly', () => ({ + ...jest.requireActual>('../assembly'), + ensureAssembly: jest.fn(), +})) +jest.mock('../community-feed', () => ({ + ...jest.requireActual>('../community-feed'), + admitFeedPost: jest.fn(), + fetchCommunityFeedTarget: jest.fn(), +})) +jest.mock('../resolve', () => ({imageToThumb: jest.fn()})) +jest.mock('../space-post', () => ({postToSpace: jest.fn()})) +jest.mock('../upload-blob', () => ({uploadBlob: jest.fn()})) + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const FEED = 'at://did:plc:community/app.bsky.feed.generator/3m2feed' +const PUBLIC_PARENT = 'at://did:plc:bob/app.bsky.feed.post/3kparent' +const COMMUNITY_PARENT = + 'at://did:plc:bob/community.blacksky.feed.post/3kparent' +const SPACE_PARENT = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kparent` + +const TOPIC = 'Should the garden stay open late?' +const STATEMENTS = ['Yes, until sunset', 'Only on weekends'] +const REF: AssemblyRef = { + rkey: '3m2kqzvnqbc2a', + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: + '["Should the garden stay open late?",["Yes, until sunset","Only on weekends"]]', +} +const CREATED_REF = {...REF, conversationId: '2demo', reportId: 'r7report'} +const CARD = { + uri: 'https://assembly.blacksky.community/2demo', + title: 'Should the garden stay open late?', + description: '1. Yes, until sunset\n2. Only on weekends', +} +const THUMB_URL = 'https://assembly.blacksky.community/api/v3/og-image/2demo' +const THUMB = { + alt: '', + source: { + id: 'thumb', + path: 'file:///cache/thumb.png', + width: 1200, + height: 630, + mime: 'image/png', + }, +} +const THUMB_BLOB = { + $type: 'blob', + ref: {$link: 'bafkreithumb'}, + mimeType: 'image/png', + size: 1234, +} +const POLLS_ARE_PUBLIC = 'Polls are only available on public posts.' +const NO_THUMB = 'Failed to attach the poll thumbnail' +const NO_IMAGE = 'The image could not be read in time' + +type Write = { + collection: string + rkey: string + value: { + text: string + reply?: unknown + embed?: {$type: string; external: Record} + } +} + +const mockEnsureAssembly = jest.mocked(ensureAssembly) +const mockImageToThumb = jest.mocked(imageToThumb) +const mockUploadBlob = jest.mocked(uploadBlob) +const mockPostToSpace = jest.mocked(postToSpace) +const mockFetchFeedTarget = jest.mocked(fetchCommunityFeedTarget) +const mockAdmitFeedPost = jest.mocked(admitFeedPost) + +const queryClient = {invalidateQueries: jest.fn()} as unknown as QueryClient + +let events: string[] +let warn: jest.SpyInstance + +function setup() { + const fetchHandler = jest.fn() + const applyWrites = jest.fn(() => { + events.push('applyWrites') + return Promise.resolve({}) + }) + const getPosts = jest.fn(() => { + events.push('getPosts') + return Promise.resolve({ + data: { + posts: [ + { + uri: PUBLIC_PARENT, + cid: 'bafyreiparent', + record: { + $type: 'app.bsky.feed.post', + text: 'hi', + createdAt: '2026-09-27T11:00:00.000Z', + }, + }, + ], + }, + }) + }) + const onStateChange = jest.fn((state: string) => { + events.push(`stage:${state}`) + }) + const onAssembly = jest.fn() + const agent = { + assertDid: 'did:plc:alice', + fetchHandler, + com: {atproto: {repo: {applyWrites}}}, + app: {bsky: {feed: {getPosts}}}, + } as unknown as AtpAgent + return {agent, fetchHandler, applyWrites, getPosts, onStateChange, onAssembly} +} + +function draft(embed: Record, text = TOPIC, id = 'post-1') { + return { + id, + richtext: {text, facets: []}, + shortenedGraphemeLength: text.length, + labels: [], + embed, + } +} + +function thread(posts: unknown[], extra: Record = {}) { + return { + posts, + postgate: {}, + threadgate: [], + blackskyOnly: false, + ...extra, + } as never +} + +function pollThread(extra: Record = {}) { + return thread([draft({poll: {statements: STATEMENTS}})], extra) +} + +function feedTarget(contentType: string, space?: string) { + return { + feed: FEED, + name: 'Garden', + serviceDid: 'did:web:feeds.example.com', + config: { + $type: 'community.blacksky.feed.config', + contentType, + visibility: 'gated', + group: 'at://did:plc:community/community.blacksky.group/community', + createdAt: '2026-08-09T12:00:00.000Z', + ...(space ? {space} : {}), + }, + } +} + +function writesOf(applyWrites: jest.Mock): Write[] { + const [{writes}] = applyWrites.mock.calls[0] as unknown as [{writes: Write[]}] + return writes +} + +function settle() { + return new Promise(resolve => setImmediate(resolve)) +} + +function expectNothingStarted(setupResult: ReturnType) { + expect(mockEnsureAssembly).not.toHaveBeenCalled() + expect(mockImageToThumb).not.toHaveBeenCalled() + expect(mockUploadBlob).not.toHaveBeenCalled() + expect(mockPostToSpace).not.toHaveBeenCalled() + expect(setupResult.applyWrites).not.toHaveBeenCalled() + expect(setupResult.fetchHandler).not.toHaveBeenCalled() + expect(setupResult.getPosts).not.toHaveBeenCalled() +} + +beforeEach(() => { + jest.resetAllMocks() + events = [] + warn = jest.spyOn(logger, 'warn').mockImplementation(() => {}) + mockEnsureAssembly.mockImplementation((agent, input) => { + events.push('ensureAssembly') + input.onRef(REF) + input.onRef(CREATED_REF) + return Promise.resolve({ref: CREATED_REF, isReplay: false}) + }) + mockImageToThumb.mockImplementation(() => { + events.push('imageToThumb') + return Promise.resolve(THUMB as never) + }) + mockUploadBlob.mockImplementation(() => { + events.push('uploadBlob') + return Promise.resolve({data: {blob: THUMB_BLOB}} as never) + }) + mockPostToSpace.mockResolvedValue({uris: ['at://space/post']}) +}) + +afterEach(() => { + jest.useRealTimers() + warn.mockRestore() +}) + +describe('publishing a post with a poll', () => { + it('writes the post with a link card to the assembly', async () => { + const ctx = setup() + + const result = await post(ctx.agent, queryClient, { + thread: thread([ + draft( + {poll: {statements: [' Yes, until sunset ', 'Only on weekends']}}, + 'Should the garden\nstay open late?', + ), + ]), + onStateChange: ctx.onStateChange, + onAssembly: ctx.onAssembly, + }) + + expect(ctx.applyWrites).toHaveBeenCalledTimes(1) + const writes = writesOf(ctx.applyWrites) + expect(writes).toHaveLength(1) + expect(writes[0].collection).toBe('app.bsky.feed.post') + expect(writes[0].value.text).toBe('Should the garden\nstay open late?') + expect(writes[0].value.embed).toStrictEqual({ + $type: 'app.bsky.embed.external', + external: {...CARD, thumb: THUMB_BLOB}, + }) + expect(result).toStrictEqual({ + uris: [`at://did:plc:alice/app.bsky.feed.post/${writes[0].rkey}`], + assembly: {conversationId: '2demo', statementCount: 2, isReplay: false}, + }) + }) + + it('starts the assembly with the topic, statements and stored reference', async () => { + const ctx = setup() + + await post(ctx.agent, queryClient, { + thread: thread([ + draft( + { + poll: { + statements: [' Yes, until sunset ', 'Only on weekends'], + assembly: REF, + }, + }, + 'Should the garden\nstay open late?', + ), + ]), + }) + + expect(mockEnsureAssembly).toHaveBeenCalledTimes(1) + expect(mockEnsureAssembly).toHaveBeenCalledWith(ctx.agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: REF, + onRef: expect.any(Function), + }) + }) + + it('creates the assembly and its thumbnail before writing the post', async () => { + const ctx = setup() + + await post(ctx.agent, queryClient, { + thread: pollThread(), + onStateChange: ctx.onStateChange, + }) + + expect(events).toEqual([ + 'stage:Processing...', + 'stage:Starting poll...', + 'ensureAssembly', + 'imageToThumb', + 'stage:Uploading link thumbnail...', + 'uploadBlob', + 'applyWrites', + ]) + expect(mockImageToThumb).toHaveBeenCalledWith(THUMB_URL) + expect(mockUploadBlob).toHaveBeenCalledWith( + ctx.agent, + 'file:///cache/thumb.png', + 'image/png', + ) + expect(fetchResolveLinkQuery).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + }) + + it('reports every change of the reference with the id of the poll post', async () => { + const ctx = setup() + + await post(ctx.agent, queryClient, { + thread: pollThread(), + onAssembly: ctx.onAssembly, + }) + + expect(ctx.onAssembly.mock.calls).toEqual([ + ['post-1', REF], + ['post-1', CREATED_REF], + ]) + }) + + it('builds the card from the assembly that was returned, and reports a replay', async () => { + const ctx = setup() + const stored = {...REF, conversationId: '1stale'} + mockEnsureAssembly.mockResolvedValue({ref: CREATED_REF, isReplay: true}) + + const result = await post(ctx.agent, queryClient, { + thread: thread([ + draft({poll: {statements: STATEMENTS, assembly: stored}}), + ]), + onAssembly: ctx.onAssembly, + }) + + expect(mockEnsureAssembly).toHaveBeenCalledWith( + ctx.agent, + expect.objectContaining({ref: stored}), + ) + expect(writesOf(ctx.applyWrites)[0].value.embed?.external.uri).toBe( + CARD.uri, + ) + expect(result.assembly).toStrictEqual({ + conversationId: '2demo', + statementCount: 2, + isReplay: true, + }) + expect(ctx.onAssembly).not.toHaveBeenCalled() + }) + + it('rethrows a failed assembly unchanged and writes nothing', async () => { + const ctx = setup() + const error = new AssemblyError('quota', 'create') + mockEnsureAssembly.mockImplementation((agent, input) => { + input.onRef(REF) + return Promise.reject(error) + }) + + await expect( + post(ctx.agent, queryClient, { + thread: pollThread(), + onAssembly: ctx.onAssembly, + }), + ).rejects.toBe(error) + + expect(ctx.onAssembly.mock.calls).toEqual([['post-1', REF]]) + expect(ctx.applyWrites).not.toHaveBeenCalled() + expect(mockImageToThumb).not.toHaveBeenCalled() + expect(mockUploadBlob).not.toHaveBeenCalled() + }) + + it('leaves a post without a poll alone', async () => { + const ctx = setup() + + const result = await post(ctx.agent, queryClient, { + thread: thread([draft({})]), + onStateChange: ctx.onStateChange, + onAssembly: ctx.onAssembly, + }) + + const writes = writesOf(ctx.applyWrites) + expect(writes[0].value.embed).toBeUndefined() + expect(result).toStrictEqual({ + uris: [`at://did:plc:alice/app.bsky.feed.post/${writes[0].rkey}`], + assembly: undefined, + }) + expect(events).toEqual(['stage:Processing...', 'applyWrites']) + expect(mockEnsureAssembly).not.toHaveBeenCalled() + expect(ctx.onAssembly).not.toHaveBeenCalled() + }) + + it('uses the text of the post that carries the poll as the topic', async () => { + const ctx = setup() + + const result = await post(ctx.agent, queryClient, { + thread: thread([ + draft({}, 'Some context first', 'post-1'), + draft({poll: {statements: STATEMENTS}}, TOPIC, 'post-2'), + ]), + onAssembly: ctx.onAssembly, + }) + + expect(mockEnsureAssembly).toHaveBeenCalledWith( + ctx.agent, + expect.objectContaining({topic: TOPIC, statements: STATEMENTS}), + ) + expect(ctx.onAssembly.mock.calls).toEqual([ + ['post-2', REF], + ['post-2', CREATED_REF], + ]) + const writes = writesOf(ctx.applyWrites) + expect(writes.map(w => w.value.text)).toEqual(['Some context first', TOPIC]) + expect(writes[0].value.embed).toBeUndefined() + expect(writes[1].value.embed).toStrictEqual({ + $type: 'app.bsky.embed.external', + external: {...CARD, thumb: THUMB_BLOB}, + }) + const first = {uri: result.uris[0], cid: 'bafyreifake'} + expect(writes[1].value.reply).toEqual({root: first, parent: first}) + }) + + it('admits a poll post to a feed of public records', async () => { + const ctx = setup() + const target = feedTarget('publicRecord') + + const result = await post(ctx.agent, queryClient, { + thread: pollThread({communityFeed: target}), + }) + + expect(writesOf(ctx.applyWrites)[0].value.embed?.external.uri).toBe( + CARD.uri, + ) + expect(mockAdmitFeedPost).toHaveBeenCalledTimes(1) + expect(mockAdmitFeedPost).toHaveBeenCalledWith( + ctx.agent, + target, + result.uris[0], + 'bafyreifake', + ) + }) +}) + +describe('replying with a poll', () => { + it('waits for the parent before starting the assembly', async () => { + const ctx = setup() + let release: (value: unknown) => void = () => {} + ctx.getPosts.mockImplementation(() => { + events.push('getPosts') + return new Promise(resolve => { + release = resolve + }) as never + }) + + const pending = post(ctx.agent, queryClient, { + thread: pollThread(), + replyTo: PUBLIC_PARENT, + onStateChange: ctx.onStateChange, + }) + await settle() + + expect(events).toEqual(['stage:Processing...', 'getPosts']) + + release({data: {posts: [{uri: PUBLIC_PARENT, cid: 'bafyreiparent'}]}}) + await pending + + expect(events).toEqual([ + 'stage:Processing...', + 'getPosts', + 'stage:Starting poll...', + 'ensureAssembly', + 'imageToThumb', + 'stage:Uploading link thumbnail...', + 'uploadBlob', + 'applyWrites', + ]) + const parent = {uri: PUBLIC_PARENT, cid: 'bafyreiparent'} + expect(writesOf(ctx.applyWrites)[0].value.reply).toEqual({ + root: parent, + parent, + }) + }) + + it('starts no assembly when the parent is gone', async () => { + const ctx = setup() + ctx.getPosts.mockImplementation(() => + Promise.resolve({data: {posts: []}} as never), + ) + + await expect( + post(ctx.agent, queryClient, { + thread: pollThread(), + replyTo: PUBLIC_PARENT, + onStateChange: ctx.onStateChange, + onAssembly: ctx.onAssembly, + }), + ).rejects.toBeInstanceOf(ReplyDeletedError) + + expect(events).toEqual(['stage:Processing...']) + expect(mockEnsureAssembly).not.toHaveBeenCalled() + expect(ctx.onAssembly).not.toHaveBeenCalled() + expect(ctx.applyWrites).not.toHaveBeenCalled() + }) +}) + +describe('the poll thumbnail', () => { + it.each([ + { + name: 'the image cannot be read', + arrange: () => mockImageToThumb.mockResolvedValue(undefined), + uploads: 0, + reason: NO_IMAGE, + }, + { + name: 'fetching the image throws', + arrange: () => mockImageToThumb.mockRejectedValue(new Error('offline')), + uploads: 0, + reason: 'offline', + }, + { + name: 'the upload fails', + arrange: () => mockUploadBlob.mockRejectedValue(new Error('too large')), + uploads: 1, + reason: 'too large', + }, + ])('is left off when $name', async ({arrange, uploads, reason}) => { + const ctx = setup() + arrange() + + const result = await post(ctx.agent, queryClient, {thread: pollThread()}) + + expect(mockUploadBlob).toHaveBeenCalledTimes(uploads) + expect(ctx.applyWrites).toHaveBeenCalledTimes(1) + expect(writesOf(ctx.applyWrites)[0].value.embed).toStrictEqual({ + $type: 'app.bsky.embed.external', + external: {...CARD, thumb: undefined}, + }) + expect(result.assembly).toStrictEqual({ + conversationId: '2demo', + statementCount: 2, + isReplay: false, + }) + expect(warn.mock.calls).toEqual([[NO_THUMB, {safeMessage: reason}]]) + }) + + it('is given up after five seconds', async () => { + jest.useFakeTimers() + const ctx = setup() + mockImageToThumb.mockImplementation(() => new Promise(() => {})) + + const pending = post(ctx.agent, queryClient, {thread: pollThread()}) + + await jest.advanceTimersByTimeAsync(4999) + expect(mockImageToThumb).toHaveBeenCalledWith(THUMB_URL) + expect(ctx.applyWrites).not.toHaveBeenCalled() + + await jest.advanceTimersByTimeAsync(1) + await pending + + expect(mockUploadBlob).not.toHaveBeenCalled() + expect(writesOf(ctx.applyWrites)[0].value.embed).toStrictEqual({ + $type: 'app.bsky.embed.external', + external: {...CARD, thumb: undefined}, + }) + expect(warn.mock.calls).toEqual([[NO_THUMB, {safeMessage: NO_IMAGE}]]) + }) + + it('leaves no timer behind once the image arrives', async () => { + jest.useFakeTimers() + const ctx = setup() + + await post(ctx.agent, queryClient, {thread: pollThread()}) + + expect(mockUploadBlob).toHaveBeenCalledTimes(1) + expect(jest.getTimerCount()).toBe(0) + }) +}) + +describe('a poll outside the public path', () => { + it.each([ + {name: 'a Blacksky Only post', extra: {blackskyOnly: true}}, + { + name: 'a community feed', + extra: {communityFeed: feedTarget('communityRecord')}, + }, + {name: 'a reply to a community post', replyTo: COMMUNITY_PARENT}, + {name: 'a private space', extra: {communitySpaceUri: SPACE}}, + {name: 'a reply to a space post', replyTo: SPACE_PARENT}, + { + name: 'a feed backed by a space', + extra: {communityFeed: feedTarget('communityRecord', SPACE)}, + }, + ])('is refused for $name before anything starts', async input => { + const ctx = setup() + + await expect( + post(ctx.agent, queryClient, { + thread: pollThread(input.extra), + replyTo: input.replyTo, + onAssembly: ctx.onAssembly, + }), + ).rejects.toThrow(new Error(POLLS_ARE_PUBLIC)) + + expectNothingStarted(ctx) + expect(ctx.onAssembly).not.toHaveBeenCalled() + }) + + it('is refused when any post of the thread has one', async () => { + const ctx = setup() + + await expect( + post(ctx.agent, queryClient, { + thread: thread( + [ + draft({}, 'Some context first', 'post-1'), + draft({poll: {statements: STATEMENTS}}, TOPIC, 'post-2'), + ], + {blackskyOnly: true}, + ), + }), + ).rejects.toThrow(new Error(POLLS_ARE_PUBLIC)) + + expectNothingStarted(ctx) + }) + + it('is refused for a quote of a community post', async () => { + const ctx = setup() + + await expect( + post(ctx.agent, queryClient, { + thread: thread([ + draft({ + poll: {statements: STATEMENTS}, + quote: {type: 'link', uri: COMMUNITY_PARENT}, + }), + ]), + }), + ).rejects.toThrow(new Error(POLLS_ARE_PUBLIC)) + + expectNothingStarted(ctx) + }) + + it('is refused for a community feed that is looked up at publish', async () => { + const ctx = setup() + mockFetchFeedTarget.mockResolvedValue( + feedTarget('communityRecord') as never, + ) + + await expect( + post(ctx.agent, queryClient, { + thread: pollThread({communityFeedUri: FEED}), + }), + ).rejects.toThrow(new Error(POLLS_ARE_PUBLIC)) + + expect(mockFetchFeedTarget).toHaveBeenCalledWith(ctx.agent, FEED) + expectNothingStarted(ctx) + }) +}) + +describe('a poll with another attachment', () => { + const COMBINED = + 'A poll cannot be combined with media, a link card or a quote.' + const attachments = [ + {name: 'media', extra: {media: {type: 'gif', gif: {}, alt: ''}}}, + { + name: 'a link card', + extra: {link: {type: 'link', uri: 'https://example.com'}}, + }, + { + name: 'a quote', + extra: { + quote: {type: 'link', uri: 'https://bsky.app/profile/a.test/post/3k'}, + }, + }, + ] + + it.each(attachments)( + 'is refused with $name before anything starts', + async ({extra}) => { + const ctx = setup() + + await expect( + post(ctx.agent, queryClient, { + thread: thread([draft({poll: {statements: STATEMENTS}, ...extra})]), + }), + ).rejects.toThrow(new Error(COMBINED)) + + expectNothingStarted(ctx) + }, + ) + + it.each(attachments)( + 'is refused with $name when the embed is built', + async ({extra}) => { + const ctx = setup() + + await expect( + resolveEmbed( + ctx.agent, + queryClient, + draft({ + poll: {statements: STATEMENTS, assembly: CREATED_REF}, + ...extra, + }) as never, + undefined, + ), + ).rejects.toThrow(new Error(COMBINED)) + + expect(mockImageToThumb).not.toHaveBeenCalled() + expect(fetchResolveLinkQuery).not.toHaveBeenCalled() + }, + ) +}) + +describe('poll invariants', () => { + it('refuses two polls in one thread before anything starts', async () => { + const ctx = setup() + + await expect( + post(ctx.agent, queryClient, { + thread: thread([ + draft({poll: {statements: STATEMENTS}}, TOPIC, 'post-1'), + draft({poll: {statements: ['Another']}}, 'Second', 'post-2'), + ]), + }), + ).rejects.toThrow(new Error('A thread can only have one poll.')) + + expectNothingStarted(ctx) + }) + + it.each([ + {name: 'no reference', assembly: undefined}, + {name: 'a reference without a conversation', assembly: REF}, + ])('refuses to build the embed of a poll with $name', async ({assembly}) => { + const ctx = setup() + + await expect( + resolveEmbed( + ctx.agent, + queryClient, + draft({poll: {statements: STATEMENTS, assembly}}) as never, + undefined, + ), + ).rejects.toThrow( + new Error('A poll cannot be posted before its assembly exists'), + ) + + expect(mockImageToThumb).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/api/__tests__/assembly.test.ts b/src/lib/api/__tests__/assembly.test.ts new file mode 100644 index 000000000..b5208ce18 --- /dev/null +++ b/src/lib/api/__tests__/assembly.test.ts @@ -0,0 +1,1340 @@ +import {type AtpAgent} from '@atproto/api' +import {TID} from '@atproto/common-web' +import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals' + +import { + ASSEMBLY_CONVERSATION_COLLECTION, + ASSEMBLY_CREATE_LXM, + AssemblyError, + assemblyFingerprint, + assemblyReportUrl, + assemblyThumbUrl, + assemblyUrl, + buildAssemblyExternal, + ensureAssembly, + isAssemblyConversationId, +} from '#/lib/api/assembly' +import {type AssemblyRef} from '#/lib/api/poll' +import {parseEmbedPlayerFromUrl} from '#/lib/strings/embed-player' + +jest.mock('#/env', () => mockEnv('https://assembly.blacksky.community')) + +function mockEnv(url: string) { + return { + ...jest.requireActual>('#/env'), + ASSEMBLY_URL: url, + ASSEMBLY_SERVICE_DID: 'did:web:assembly.blacksky.community', + } +} + +const NOW = new Date('2026-09-27T12:00:00.000Z') +const NOW_SECONDS = 1790510400 +const DID = 'did:plc:author' +const CID = 'bafyreiconversation' +const RKEY = '3m2kqzvnqbc2a' +const NEXT_RKEY = '3m2kqzvnqbd2a' +const TOPIC = 'Should the garden stay open late?' +const STATEMENTS = ['Yes, until sunset', 'Only on weekends'] +const FINGERPRINT = + '["Should the garden stay open late?",["Yes, until sunset","Only on weekends"]]' +const ENDPOINT = + 'https://assembly.blacksky.community/api/v3/atproto/conversations' +const AT_URI = `at://did:plc:author/community.blacksky.assembly.conversation/${RKEY}` +const BODY = JSON.stringify({ + topic: TOPIC, + statements: STATEMENTS, + conversation: {at_uri: AT_URI, at_cid: CID}, +}) +const INCOMPLETE = {error: 'polis_err_atproto_statement_records_incomplete'} +const CREATED = {conversation_id: '2demo', report_id: 'r7report', created: true} + +type RecordInput = { + repo: string + collection: string + rkey: string + record?: Record +} +type TokenInput = {aud: string; lxm: string; exp: number} + +const fetchMock = jest.fn() + +function reply(status: number, body: unknown) { + return { + ok: status < 400, + status, + text: () => + Promise.resolve(typeof body === 'string' ? body : JSON.stringify(body)), + } as Response +} + +function setup() { + const events: string[] = [] + const refs: AssemblyRef[] = [] + let tokens = 0 + const putRecord = jest.fn((input: RecordInput) => { + events.push('putRecord') + return Promise.resolve({ + data: { + uri: `at://${input.repo}/${input.collection}/${input.rkey}`, + cid: CID, + }, + }) + }) + const deleteRecord = jest.fn<(input: RecordInput) => Promise<{data: object}>>( + () => { + events.push('deleteRecord') + return Promise.resolve({data: {}}) + }, + ) + const getServiceAuth = jest.fn< + (input: TokenInput) => Promise<{data: {token: string}}> + >(() => { + events.push('getServiceAuth') + tokens += 1 + return Promise.resolve({data: {token: `token-${tokens}`}}) + }) + const onRef = jest.fn((ref: AssemblyRef) => { + events.push('onRef') + refs.push(ref) + }) + const pause = jest.fn<(ms: number) => Promise>(() => { + events.push('pause') + return Promise.resolve() + }) + const agent = { + assertDid: DID, + dispatchUrl: 'https://pds.example/', + com: { + atproto: { + repo: {putRecord, deleteRecord}, + server: {getServiceAuth}, + }, + }, + } as unknown as AtpAgent + return { + agent, + events, + refs, + putRecord, + deleteRecord, + getServiceAuth, + onRef, + pause, + } +} + +function respondWith(...responses: Response[]) { + for (const response of responses) { + fetchMock.mockImplementationOnce(() => Promise.resolve(response)) + } +} + +function describeError(error: unknown) { + const fields: Record = {} + if (error instanceof Error) { + for (const key of Object.getOwnPropertyNames(error)) { + if (key !== 'stack') fields[key] = Reflect.get(error, key) + } + } + return fields +} + +function sentRequest(call: number) { + const [url, init] = fetchMock.mock.calls[call] + return {url, init: init as RequestInit} +} + +beforeEach(() => { + jest.useFakeTimers({now: NOW}) + global.fetch = fetchMock + fetchMock.mockReset() + jest.spyOn(TID, 'nextStr').mockReturnValue(RKEY) +}) + +afterEach(() => { + jest.useRealTimers() + jest.restoreAllMocks() +}) + +describe('assemblyFingerprint', () => { + it('is the JSON of the topic and the ordered statements', () => { + expect(assemblyFingerprint(TOPIC, STATEMENTS)).toBe(FINGERPRINT) + expect(assemblyFingerprint('T', ['B', 'A'])).toBe('["T",["B","A"]]') + expect(assemblyFingerprint('T', ['A', 'B'])).toBe('["T",["A","B"]]') + }) + + it('ignores differences that normalisation removes', () => { + expect(assemblyFingerprint(' T \n', [' café '])).toBe('["T",["café"]]') + }) + + it('keeps the topic apart from the statements', () => { + expect(assemblyFingerprint('A', ['B'])).toBe('["A",["B"]]') + expect(assemblyFingerprint('A', [])).toBe('["A",[]]') + expect(assemblyFingerprint('A","B', [])).toBe('["A\\",\\"B",[]]') + }) +}) + +describe('isAssemblyConversationId', () => { + it.each(['2demo', '7abcDEF123', '12345', '0zzzzzzzzzzzzzzz'])( + 'accepts %s', + value => { + expect(isAssemblyConversationId(value)).toBe(true) + }, + ) + + it.each([ + 'demo2', + 'a2demo', + '2dem', + '2de-mo', + '2demo/x', + ' 2demo', + '2demo\n', + '', + 12345, + null, + undefined, + ['2demo'], + ])('rejects %p', value => { + expect(isAssemblyConversationId(value)).toBe(false) + }) +}) + +describe('assembly links', () => { + it('builds the conversation, results and thumbnail addresses', () => { + expect(assemblyUrl('2demo')).toBe( + 'https://assembly.blacksky.community/2demo', + ) + expect(assemblyReportUrl('r7report')).toBe( + 'https://assembly.blacksky.community/report/r7report', + ) + expect(assemblyThumbUrl('2demo')).toBe( + 'https://assembly.blacksky.community/api/v3/og-image/2demo', + ) + }) + + it.each(['2demo', '7abcDEF123', '12345', '0zzzzzzzzzzzzzzz'])( + 'links %s where the in-app card finds it', + value => { + expect(parseEmbedPlayerFromUrl(assemblyUrl(value))).toStrictEqual({ + type: 'assembly_conversation', + source: 'assembly', + playerUri: `https://assembly.blacksky.community/${value}`, + hideDetails: false, + }) + }, + ) + + it('keeps an identifier inside its path segment', () => { + expect(assemblyUrl('2demo/../x')).toBe( + 'https://assembly.blacksky.community/2demo%2F..%2Fx', + ) + expect(assemblyReportUrl('r7?x=1')).toBe( + 'https://assembly.blacksky.community/report/r7%3Fx%3D1', + ) + }) +}) + +describe('buildAssemblyExternal', () => { + it('links the conversation and lists the statements by number', () => { + expect( + buildAssemblyExternal({ + conversationId: '2demo', + topic: TOPIC, + statements: STATEMENTS, + }), + ).toStrictEqual({ + uri: 'https://assembly.blacksky.community/2demo', + title: 'Should the garden stay open late?', + description: '1. Yes, until sunset\n2. Only on weekends', + }) + }) + + it('numbers a single statement', () => { + expect( + buildAssemblyExternal({ + conversationId: '2demo', + topic: 'T', + statements: ['Only one'], + }).description, + ).toBe('1. Only one') + }) +}) + +describe('AssemblyError', () => { + it('carries the code and the stage', () => { + const error = new AssemblyError('quota', 'create') + expect(error).toBeInstanceOf(AssemblyError) + expect(error).toBeInstanceOf(Error) + expect(error.name).toBe('AssemblyError') + expect(error.code).toBe('quota') + expect(error.stage).toBe('create') + }) +}) + +describe('ensureAssembly', () => { + it('writes the record, asks for a token and creates the conversation', async () => { + const {agent, events, putRecord, deleteRecord, getServiceAuth, onRef} = + setup() + respondWith(reply(201, CREATED)) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }) + + expect(ASSEMBLY_CONVERSATION_COLLECTION).toBe( + 'community.blacksky.assembly.conversation', + ) + expect(ASSEMBLY_CREATE_LXM).toBe( + 'community.blacksky.assembly.createConversation', + ) + expect(putRecord.mock.calls).toStrictEqual([ + [ + { + repo: 'did:plc:author', + collection: 'community.blacksky.assembly.conversation', + rkey: RKEY, + record: { + $type: 'community.blacksky.assembly.conversation', + topic: TOPIC, + authRequired: true, + createdAt: '2026-09-27T12:00:00.000Z', + }, + }, + ], + ]) + expect(getServiceAuth.mock.calls).toStrictEqual([ + [ + { + aud: 'did:web:assembly.blacksky.community', + lxm: 'community.blacksky.assembly.createConversation', + exp: NOW_SECONDS + 60, + }, + ], + ]) + expect(fetchMock).toHaveBeenCalledTimes(1) + const {url, init} = sentRequest(0) + expect(url).toBe(ENDPOINT) + expect(init.method).toBe('POST') + expect(init.headers).toStrictEqual({ + Authorization: 'Bearer token-1', + 'Content-Type': 'application/json', + }) + expect(init.body).toBe( + '{"topic":"Should the garden stay open late?","statements":["Yes, until sunset","Only on weekends"],"conversation":{"at_uri":"at://did:plc:author/community.blacksky.assembly.conversation/3m2kqzvnqbc2a","at_cid":"bafyreiconversation"}}', + ) + expect(init.signal).toBeInstanceOf(AbortSignal) + expect(init.signal?.aborted).toBe(false) + expect(deleteRecord).not.toHaveBeenCalled() + expect(result).toStrictEqual({ + ref: { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + }, + isReplay: false, + }) + expect(events).toStrictEqual([ + 'onRef', + 'putRecord', + 'getServiceAuth', + 'onRef', + ]) + expect(jest.getTimerCount()).toBe(0) + }) + + it('reports the reference before the first request and again with the conversation', async () => { + const {agent, putRecord, getServiceAuth, onRef} = setup() + const seenAtFirstReport: number[] = [] + onRef.mockImplementationOnce(() => { + seenAtFirstReport.push( + putRecord.mock.calls.length, + getServiceAuth.mock.calls.length, + fetchMock.mock.calls.length, + ) + }) + respondWith(reply(201, CREATED)) + + await ensureAssembly(agent, {topic: TOPIC, statements: STATEMENTS, onRef}) + + expect(seenAtFirstReport).toStrictEqual([0, 0, 0]) + expect(onRef.mock.calls).toStrictEqual([ + [ + { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + }, + ], + [ + { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + }, + ], + ]) + }) + + it('reports a replay when the server did not create the conversation', async () => { + const {agent, onRef} = setup() + respondWith( + reply(200, { + conversation_id: '2demo', + report_id: 'r7report', + created: false, + }), + ) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }) + + expect(result.isReplay).toBe(true) + expect(result.ref.conversationId).toBe('2demo') + }) + + it.each([ + {answer: 'leaves it out', status: 200, body: {conversation_id: '2demo'}}, + { + answer: 'says null', + status: 200, + body: {conversation_id: '2demo', created: null}, + }, + { + answer: 'says true', + status: 200, + body: {conversation_id: '2demo', created: true}, + }, + ])( + 'reports a new conversation when the server $answer', + async ({status, body}) => { + const {agent, onRef} = setup() + respondWith(reply(status, body)) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }) + + expect(result.isReplay).toBe(false) + expect(result.ref.conversationId).toBe('2demo') + }, + ) + + it.each([ + {report: 'absent', body: {conversation_id: '2demo', created: true}}, + { + report: 'null', + body: {conversation_id: '2demo', report_id: null, created: true}, + }, + { + report: 'empty', + body: {conversation_id: '2demo', report_id: '', created: true}, + }, + { + report: 'not text', + body: {conversation_id: '2demo', report_id: 7, created: true}, + }, + ])('leaves the results reference out when it is $report', async ({body}) => { + const {agent, onRef} = setup() + respondWith(reply(201, body)) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }) + + const expected = { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + } + expect(result).toStrictEqual({ref: expected, isReplay: false}) + expect(onRef.mock.calls[1]).toStrictEqual([expected]) + }) + + it('sends the normalised topic and statements', async () => { + const {agent, putRecord, onRef} = setup() + respondWith(reply(201, CREATED)) + + const result = await ensureAssembly(agent, { + topic: ` ${TOPIC}\n`, + statements: [' Yes, until sunset ', 'Only on weekends\n'], + onRef, + }) + + expect(putRecord.mock.calls[0][0].record?.topic).toBe(TOPIC) + expect(sentRequest(0).init.body).toBe(BODY) + expect(result.ref.fingerprint).toBe(FINGERPRINT) + }) + + it('makes no request when the reference already has its conversation', async () => { + const {agent, putRecord, deleteRecord, getServiceAuth, onRef} = setup() + const ref = { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + } + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref, + onRef, + }) + + expect(result).toStrictEqual({ref, isReplay: true}) + expect(putRecord).not.toHaveBeenCalled() + expect(deleteRecord).not.toHaveBeenCalled() + expect(getServiceAuth).not.toHaveBeenCalled() + expect(fetchMock).not.toHaveBeenCalled() + expect(onRef).not.toHaveBeenCalled() + expect(TID.nextStr).not.toHaveBeenCalled() + }) + + it('repeats the identical record and request on a retry', async () => { + const {agent, refs, putRecord, deleteRecord, onRef} = setup() + fetchMock.mockImplementationOnce(() => + Promise.reject(new TypeError('Network request failed')), + ) + await expect( + ensureAssembly(agent, {topic: TOPIC, statements: STATEMENTS, onRef}), + ).rejects.toMatchObject({code: 'network', stage: 'create'}) + expect(refs).toStrictEqual([ + { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + }, + ]) + + jest.setSystemTime(new Date('2026-09-27T12:05:00.000Z')) + jest.mocked(TID.nextStr).mockReturnValue(NEXT_RKEY) + respondWith(reply(200, {...CREATED, created: false})) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: refs[0], + onRef, + }) + + expect(putRecord).toHaveBeenCalledTimes(2) + expect(JSON.stringify(putRecord.mock.calls[1][0])).toBe( + JSON.stringify(putRecord.mock.calls[0][0]), + ) + expect(putRecord.mock.calls[1][0]).toStrictEqual({ + repo: DID, + collection: 'community.blacksky.assembly.conversation', + rkey: RKEY, + record: { + $type: 'community.blacksky.assembly.conversation', + topic: TOPIC, + authRequired: true, + createdAt: '2026-09-27T12:00:00.000Z', + }, + }) + expect(sentRequest(0).init.body).toBe(BODY) + expect(sentRequest(1).init.body).toBe(BODY) + expect(TID.nextStr).toHaveBeenCalledTimes(1) + expect(deleteRecord).not.toHaveBeenCalled() + expect(result).toStrictEqual({ + ref: { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + }, + isReplay: true, + }) + }) + + it('starts over with a new record when the text changed', async () => { + const {agent, events, putRecord, deleteRecord, onRef} = setup() + jest.mocked(TID.nextStr).mockReturnValue(NEXT_RKEY) + respondWith(reply(201, CREATED)) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: ['Yes, until sunset', 'Never'], + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + }, + onRef, + }) + + const fingerprint = + '["Should the garden stay open late?",["Yes, until sunset","Never"]]' + expect(deleteRecord.mock.calls).toStrictEqual([ + [ + { + repo: DID, + collection: 'community.blacksky.assembly.conversation', + rkey: RKEY, + }, + ], + ]) + expect(putRecord.mock.calls[0][0].rkey).toBe(NEXT_RKEY) + expect(putRecord.mock.calls[0][0].record?.createdAt).toBe( + '2026-09-27T12:00:00.000Z', + ) + expect(onRef.mock.calls[0]).toStrictEqual([ + { + rkey: NEXT_RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint, + }, + ]) + expect(sentRequest(0).init.body).toBe( + '{"topic":"Should the garden stay open late?","statements":["Yes, until sunset","Never"],"conversation":{"at_uri":"at://did:plc:author/community.blacksky.assembly.conversation/3m2kqzvnqbd2a","at_cid":"bafyreiconversation"}}', + ) + expect(result.ref.rkey).toBe(NEXT_RKEY) + expect(result.ref.fingerprint).toBe(fingerprint) + expect(events).toStrictEqual([ + 'onRef', + 'deleteRecord', + 'putRecord', + 'getServiceAuth', + 'onRef', + ]) + }) + + it('treats a reordering of the statements as a change', async () => { + const {agent, putRecord, deleteRecord, onRef} = setup() + jest.mocked(TID.nextStr).mockReturnValue(NEXT_RKEY) + respondWith(reply(201, CREATED)) + + await ensureAssembly(agent, { + topic: TOPIC, + statements: ['Only on weekends', 'Yes, until sunset'], + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + }, + onRef, + }) + + expect(deleteRecord.mock.calls[0][0].rkey).toBe(RKEY) + expect(putRecord.mock.calls[0][0].rkey).toBe(NEXT_RKEY) + }) + + it('continues when the old record cannot be deleted', async () => { + const {agent, putRecord, deleteRecord, onRef} = setup() + jest.mocked(TID.nextStr).mockReturnValue(NEXT_RKEY) + deleteRecord.mockImplementationOnce(() => + Promise.reject(new Error('Network request failed')), + ) + respondWith(reply(201, CREATED)) + + const result = await ensureAssembly(agent, { + topic: 'A different question', + statements: STATEMENTS, + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + }, + onRef, + }) + + expect(deleteRecord).toHaveBeenCalledTimes(1) + expect(putRecord.mock.calls[0][0].rkey).toBe(NEXT_RKEY) + expect(result.ref.conversationId).toBe('2demo') + }) + + it('keeps the record of a conversation that already exists when the text changed', async () => { + const {agent, putRecord, deleteRecord, onRef} = setup() + jest.mocked(TID.nextStr).mockReturnValue(NEXT_RKEY) + respondWith(reply(201, {conversation_id: '3other', created: true})) + + const result = await ensureAssembly(agent, { + topic: 'A different question', + statements: STATEMENTS, + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + }, + onRef, + }) + + const fresh = { + rkey: NEXT_RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: + '["A different question",["Yes, until sunset","Only on weekends"]]', + } + expect(deleteRecord).not.toHaveBeenCalled() + expect(putRecord.mock.calls[0][0].rkey).toBe(NEXT_RKEY) + expect(onRef.mock.calls).toStrictEqual([ + [fresh], + [{...fresh, conversationId: '3other'}], + ]) + expect(result).toStrictEqual({ + ref: {...fresh, conversationId: '3other'}, + isReplay: false, + }) + }) + + it('asks the server again when a stored conversation id is not usable', async () => { + const {agent, putRecord, deleteRecord, onRef} = setup() + respondWith(reply(200, {...CREATED, created: false})) + + const result = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + conversationId: 'not/an/id', + }, + onRef, + }) + + expect(TID.nextStr).not.toHaveBeenCalled() + expect(deleteRecord).not.toHaveBeenCalled() + expect(putRecord.mock.calls[0][0].rkey).toBe(RKEY) + expect(putRecord.mock.calls[0][0].record?.createdAt).toBe( + '2026-09-01T08:30:00.000Z', + ) + expect(onRef.mock.calls[0]).toStrictEqual([ + { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + }, + ]) + expect(result.ref.conversationId).toBe('2demo') + expect(result.isReplay).toBe(true) + }) + + it.each([ + [400, 'polis_err_atproto_conversation_statements_invalid', 'invalid'], + [403, 'polis_err_atproto_conversation_not_eligible', 'not_eligible'], + [400, 'polis_err_atproto_unsupported_did', 'not_eligible'], + [403, 'polis_err_atproto_record_did_mismatch', 'not_eligible'], + [410, 'polis_err_atproto_conversation_removed', 'removed'], + [429, 'polis_err_atproto_conversation_quota_exceeded', 'quota'], + ])( + 'deletes the record when the server refuses with %i %s', + async (status, error, code) => { + const {agent, events, deleteRecord, onRef, pause} = setup() + respondWith(reply(status, {error})) + + const failure = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code, stage: 'create'}) + expect(deleteRecord.mock.calls).toStrictEqual([ + [ + { + repo: DID, + collection: 'community.blacksky.assembly.conversation', + rkey: RKEY, + }, + ], + ]) + expect(events).toStrictEqual([ + 'onRef', + 'putRecord', + 'getServiceAuth', + 'deleteRecord', + ]) + expect(fetchMock).toHaveBeenCalledTimes(1) + }, + ) + + it('starts over with a new record after a conflict', async () => { + const {agent, events, refs, putRecord, deleteRecord, onRef} = setup() + jest + .spyOn(TID, 'nextStr') + .mockReturnValueOnce(RKEY) + .mockReturnValueOnce(NEXT_RKEY) + respondWith( + reply(409, { + error: 'polis_err_atproto_conversation_idempotency_mismatch', + }), + reply(201, CREATED), + ) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'conflict', stage: 'create'}) + expect(events).toStrictEqual([ + 'onRef', + 'putRecord', + 'getServiceAuth', + 'deleteRecord', + 'onRef', + ]) + expect(deleteRecord.mock.calls).toStrictEqual([ + [{repo: DID, collection: ASSEMBLY_CONVERSATION_COLLECTION, rkey: RKEY}], + ]) + expect(refs[1]).toStrictEqual({ + rkey: NEXT_RKEY, + createdAt: NOW.toISOString(), + fingerprint: FINGERPRINT, + }) + + const retried = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: refs[1], + onRef, + }) + + expect(putRecord.mock.calls.map(([input]) => input.rkey)).toStrictEqual([ + RKEY, + NEXT_RKEY, + ]) + expect(deleteRecord).toHaveBeenCalledTimes(1) + expect(retried.ref.conversationId).toBe('2demo') + expect(retried.ref.rkey).toBe(NEXT_RKEY) + }) + + it('keeps the record and the reference when too many requests came from one address', async () => { + const {agent, deleteRecord, onRef, refs} = setup() + respondWith( + reply(429, {error: 'polis_err_atproto_conversation_rate_limited'}), + reply(201, { + conversation_id: '2demo', + report_id: 'r2demo', + created: true, + }), + ) + + await expect( + ensureAssembly(agent, {topic: TOPIC, statements: STATEMENTS, onRef}), + ).rejects.toMatchObject({code: 'busy', stage: 'create'}) + expect(deleteRecord).toHaveBeenCalledTimes(0) + const kept = refs[refs.length - 1] + + const retried = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: kept, + onRef, + }) + + expect(retried.ref.rkey).toBe(kept.rkey) + expect(retried.ref.conversationId).toBe('2demo') + expect(deleteRecord).toHaveBeenCalledTimes(0) + }) + + it('still reports the refusal when the record cannot be deleted', async () => { + const {agent, deleteRecord, onRef} = setup() + deleteRecord.mockImplementationOnce(() => + Promise.reject(new Error('Network request failed')), + ) + respondWith( + reply(429, {error: 'polis_err_atproto_conversation_quota_exceeded'}), + ) + + await expect( + ensureAssembly(agent, {topic: TOPIC, statements: STATEMENTS, onRef}), + ).rejects.toMatchObject({code: 'quota', stage: 'create'}) + expect(deleteRecord).toHaveBeenCalledTimes(1) + }) + + it.each([ + [401, 'polis_err_atproto_auth_invalid', 'auth'], + [404, 'polis_err_not_found', 'unavailable'], + [500, 'polis_err_internal', 'unavailable'], + [502, 'bad_gateway', 'unavailable'], + [503, 'polis_err_atproto_conversations_disabled', 'unavailable'], + [503, 'polis_err_atproto_seed_publisher_unavailable', 'unavailable'], + [503, 'polis_err_atproto_did_resolution_failed', 'unavailable'], + [500, 'polis_err_atproto_statement_records_incomplete', 'unavailable'], + [204, '', 'unavailable'], + ])( + 'keeps the record and does not resend on %i %s', + async (status, error, code) => { + const {agent, deleteRecord, onRef, pause} = setup() + respondWith(reply(status, {error})) + + const failure = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code, stage: 'create'}) + expect(deleteRecord).not.toHaveBeenCalled() + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(pause).not.toHaveBeenCalled() + expect(onRef).toHaveBeenCalledTimes(1) + }, + ) + + it('does not accept a conversation from any other success status', async () => { + const {agent, deleteRecord, onRef} = setup() + respondWith(reply(202, CREATED)) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'unavailable', stage: 'create'}) + expect(onRef).toHaveBeenCalledTimes(1) + expect(deleteRecord).not.toHaveBeenCalled() + }) + + it('keeps the record when the request cannot be delivered', async () => { + const {agent, deleteRecord, onRef} = setup() + fetchMock.mockImplementationOnce(() => + Promise.reject(new TypeError('Failed to fetch')), + ) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'network', stage: 'create'}) + expect(deleteRecord).not.toHaveBeenCalled() + expect(onRef).toHaveBeenCalledTimes(1) + expect(jest.getTimerCount()).toBe(0) + }) + + it('keeps the record when the response cannot be read', async () => { + const {agent, deleteRecord, onRef} = setup() + respondWith({ + ok: true, + status: 201, + text: () => Promise.reject(new TypeError('Network request failed')), + } as Response) + + await expect( + ensureAssembly(agent, {topic: TOPIC, statements: STATEMENTS, onRef}), + ).rejects.toMatchObject({code: 'network', stage: 'create'}) + expect(deleteRecord).not.toHaveBeenCalled() + }) + + it('gives up after thirty seconds without an answer', async () => { + const {agent, deleteRecord, onRef} = setup() + fetchMock.mockImplementationOnce( + (url, init) => + new Promise((resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(new Error('Aborted')), + ) + }), + ) + let failure: unknown + const pending = ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => { + failure = e + }) + + await jest.advanceTimersByTimeAsync(0) + expect(fetchMock).toHaveBeenCalledTimes(1) + await jest.advanceTimersByTimeAsync(29999) + expect(sentRequest(0).init.signal?.aborted).toBe(false) + expect(failure).toBeUndefined() + await jest.advanceTimersByTimeAsync(1) + await pending + + expect(sentRequest(0).init.signal?.aborted).toBe(true) + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'network', stage: 'create'}) + expect(deleteRecord).not.toHaveBeenCalled() + }) + + it('gives up when the answer is still arriving after thirty seconds', async () => { + const {agent, deleteRecord, onRef} = setup() + fetchMock.mockImplementationOnce((url, init) => + Promise.resolve({ + ok: true, + status: 201, + text: () => + new Promise((resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(new Error('Aborted')), + ) + }), + } as Response), + ) + let failure: unknown + const pending = ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => { + failure = e + }) + + await jest.advanceTimersByTimeAsync(29999) + expect(failure).toBeUndefined() + expect(jest.getTimerCount()).toBe(1) + await jest.advanceTimersByTimeAsync(1) + await pending + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'network', stage: 'create'}) + expect(onRef).toHaveBeenCalledTimes(1) + expect(deleteRecord).not.toHaveBeenCalled() + expect(jest.getTimerCount()).toBe(0) + }) + + it('resends with a fresh token while the statement records are incomplete', async () => { + const { + agent, + events, + putRecord, + getServiceAuth, + deleteRecord, + onRef, + pause, + } = setup() + respondWith(reply(503, INCOMPLETE), reply(201, CREATED)) + + const result = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ) + + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(sentRequest(0).init.headers).toStrictEqual({ + Authorization: 'Bearer token-1', + 'Content-Type': 'application/json', + }) + expect(sentRequest(1).init.headers).toStrictEqual({ + Authorization: 'Bearer token-2', + 'Content-Type': 'application/json', + }) + expect(sentRequest(0).init.body).toBe(BODY) + expect(sentRequest(1).init.body).toBe(BODY) + expect(sentRequest(1).url).toBe(ENDPOINT) + expect(getServiceAuth).toHaveBeenCalledTimes(2) + expect(putRecord).toHaveBeenCalledTimes(1) + expect(deleteRecord).not.toHaveBeenCalled() + expect(pause.mock.calls).toStrictEqual([[1000]]) + expect(events).toStrictEqual([ + 'onRef', + 'putRecord', + 'getServiceAuth', + 'pause', + 'getServiceAuth', + 'onRef', + ]) + expect(result).toStrictEqual({ + ref: { + rkey: RKEY, + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: FINGERPRINT, + conversationId: '2demo', + reportId: 'r7report', + }, + isReplay: false, + }) + }) + + it('succeeds on the third attempt', async () => { + const {agent, onRef, pause} = setup() + respondWith( + reply(503, INCOMPLETE), + reply(503, INCOMPLETE), + reply(200, {...CREATED, created: false}), + ) + + const result = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ) + + expect(fetchMock).toHaveBeenCalledTimes(3) + expect(sentRequest(2).init.headers).toStrictEqual({ + Authorization: 'Bearer token-3', + 'Content-Type': 'application/json', + }) + expect(pause.mock.calls).toStrictEqual([[1000], [1000]]) + expect(result.ref.conversationId).toBe('2demo') + expect(result.isReplay).toBe(true) + }) + + it('gives up after the third incomplete attempt and keeps the record', async () => { + const {agent, getServiceAuth, deleteRecord, onRef, pause} = setup() + respondWith( + reply(503, INCOMPLETE), + reply(503, INCOMPLETE), + reply(503, INCOMPLETE), + reply(201, CREATED), + ) + + const failure = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'unavailable', stage: 'create'}) + expect(fetchMock).toHaveBeenCalledTimes(3) + expect(getServiceAuth).toHaveBeenCalledTimes(3) + expect(pause.mock.calls).toStrictEqual([[1000], [1000]]) + expect(deleteRecord).not.toHaveBeenCalled() + expect(onRef).toHaveBeenCalledTimes(1) + }) + + it('stops resending when a later attempt is refused', async () => { + const {agent, deleteRecord, onRef, pause} = setup() + respondWith( + reply(503, INCOMPLETE), + reply(403, {error: 'polis_err_atproto_conversation_not_eligible'}), + ) + + await expect( + ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ), + ).rejects.toMatchObject({code: 'not_eligible', stage: 'create'}) + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(pause.mock.calls).toStrictEqual([[1000]]) + expect(deleteRecord).toHaveBeenCalledTimes(1) + }) + + it('waits one second between attempts by default', async () => { + const {agent, getServiceAuth, onRef} = setup() + respondWith(reply(503, INCOMPLETE), reply(201, CREATED)) + + const pending = ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }) + + await jest.advanceTimersByTimeAsync(0) + expect(fetchMock).toHaveBeenCalledTimes(1) + await jest.advanceTimersByTimeAsync(999) + expect(fetchMock).toHaveBeenCalledTimes(1) + await jest.advanceTimersByTimeAsync(1) + expect(fetchMock).toHaveBeenCalledTimes(2) + await expect(pending).resolves.toMatchObject({ + ref: {conversationId: '2demo'}, + isReplay: false, + }) + expect(getServiceAuth.mock.calls.map(([input]) => input.exp)).toStrictEqual( + [NOW_SECONDS + 60, NOW_SECONDS + 61], + ) + }) + + it.each([ + { + problem: 'without a leading digit', + body: {conversation_id: 'demo2', created: true}, + }, + { + problem: 'that is too short', + body: {conversation_id: '2dem', created: true}, + }, + { + problem: 'that is not text', + body: {conversation_id: 12345, created: true}, + }, + {problem: 'that is missing', body: {created: true}}, + {problem: 'in a body that is not an object', body: ['2demo']}, + {problem: 'in a body that is not JSON', body: '2demo'}, + ])('rejects a conversation id $problem', async ({body}) => { + const {agent, deleteRecord, onRef} = setup() + respondWith(reply(201, body)) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code: 'unavailable', stage: 'create'}) + expect(onRef).toHaveBeenCalledTimes(1) + expect(deleteRecord).not.toHaveBeenCalled() + }) + + it.each([ + ['Network request failed', 'network'], + ['Record could not be written', 'unavailable'], + ])( + 'stops at the record when writing fails with %s', + async (message, code) => { + const {agent, putRecord, getServiceAuth, deleteRecord, onRef} = setup() + putRecord.mockImplementationOnce(() => Promise.reject(new Error(message))) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code, stage: 'record'}) + expect(onRef).toHaveBeenCalledTimes(1) + expect(getServiceAuth).not.toHaveBeenCalled() + expect(fetchMock).not.toHaveBeenCalled() + expect(deleteRecord).not.toHaveBeenCalled() + }, + ) + + it.each([ + ['Bad token scope', 'auth'], + ['Network request failed', 'network'], + ])('stops at the token when it fails with %s', async (message, code) => { + const {agent, getServiceAuth, deleteRecord, onRef} = setup() + getServiceAuth.mockImplementationOnce(() => + Promise.reject(new Error(message)), + ) + + const failure = await ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + onRef, + }).catch((e: unknown) => e) + + expect(failure).toBeInstanceOf(AssemblyError) + expect(failure).toMatchObject({code, stage: 'token'}) + expect(fetchMock).not.toHaveBeenCalled() + expect(deleteRecord).not.toHaveBeenCalled() + }) + + it('keeps the token out of the console and out of the error', async () => { + const {agent, onRef, pause} = setup() + const written: string[] = [] + for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) { + jest.spyOn(console, method).mockImplementation((...args: unknown[]) => { + for (const arg of args) { + written.push( + arg instanceof Error + ? `${arg.message} ${arg.stack}` + : JSON.stringify(arg), + ) + } + }) + } + respondWith( + reply(503, INCOMPLETE), + reply(403, {error: 'polis_err_atproto_conversation_not_eligible'}), + ) + fetchMock.mockImplementationOnce(() => + Promise.reject(new TypeError('Network request failed')), + ) + + const refused = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ).catch((e: unknown) => e) + const undelivered = await ensureAssembly( + agent, + {topic: TOPIC, statements: STATEMENTS, onRef}, + {pause}, + ).catch((e: unknown) => e) + + expect(sentRequest(1).init.headers).toStrictEqual({ + Authorization: 'Bearer token-2', + 'Content-Type': 'application/json', + }) + expect(sentRequest(2).init.headers).toStrictEqual({ + Authorization: 'Bearer token-3', + 'Content-Type': 'application/json', + }) + expect(refused).toBeInstanceOf(AssemblyError) + expect(undelivered).toBeInstanceOf(AssemblyError) + expect(describeError(refused)).toStrictEqual({ + message: 'not_eligible', + name: 'AssemblyError', + code: 'not_eligible', + stage: 'create', + }) + expect(describeError(undelivered)).toStrictEqual({ + message: 'network', + name: 'AssemblyError', + code: 'network', + stage: 'create', + }) + expect(written.join('\n')).not.toContain('token-') + }) +}) + +describe('a configured assembly address', () => { + afterEach(() => { + jest.resetModules() + jest.doMock('#/env', () => mockEnv('https://assembly.blacksky.community')) + }) + + it('drops the trailing slash before building addresses', async () => { + jest.resetModules() + jest.doMock('#/env', () => mockEnv('http://localhost:5000/')) + const local = jest.requireActual<{ + ensureAssembly: typeof ensureAssembly + assemblyUrl: typeof assemblyUrl + assemblyReportUrl: typeof assemblyReportUrl + assemblyThumbUrl: typeof assemblyThumbUrl + }>('#/lib/api/assembly') + const {agent, onRef} = setup() + respondWith(reply(201, CREATED)) + + await local.ensureAssembly(agent, { + topic: TOPIC, + statements: STATEMENTS, + ref: { + rkey: RKEY, + createdAt: '2026-09-01T08:30:00.000Z', + fingerprint: FINGERPRINT, + }, + onRef, + }) + + expect(sentRequest(0).url).toBe( + 'http://localhost:5000/api/v3/atproto/conversations', + ) + expect(local.assemblyUrl('2demo')).toBe('http://localhost:5000/2demo') + expect(local.assemblyReportUrl('r7report')).toBe( + 'http://localhost:5000/report/r7report', + ) + expect(local.assemblyThumbUrl('2demo')).toBe( + 'http://localhost:5000/api/v3/og-image/2demo', + ) + }) +}) diff --git a/src/lib/api/__tests__/poll.test.ts b/src/lib/api/__tests__/poll.test.ts new file mode 100644 index 000000000..202b5448e --- /dev/null +++ b/src/lib/api/__tests__/poll.test.ts @@ -0,0 +1,239 @@ +import {countGraphemes} from 'unicode-segmenter/grapheme' + +import { + decodePollDraft, + getStatementIssue, + getStatementIssues, + inspectText, + isPollDraftPublishable, + isPollTopicPublishable, + normalizePollText, + POLL_MAX_STATEMENTS, + POLL_STATEMENT_MAX_BYTES, + POLL_STATEMENT_MAX_CHARS, + POLL_STATEMENT_MAX_GRAPHEMES, + POLL_TOPIC_MAX_BYTES, + POLL_TOPIC_MAX_GRAPHEMES, + pollStatementsForPublish, + pollTopicFromText, +} from '#/lib/api/poll' + +const ASTRAL = '\u{10348}' +const COMBINING_ACUTE = '́' + +describe('inspectText', () => { + it('counts UTF-8 bytes for every code point width', () => { + expect(inspectText('a').bytes).toBe(1) + expect(inspectText('é').bytes).toBe(2) + expect(inspectText('€').bytes).toBe(3) + expect(inspectText(ASTRAL).bytes).toBe(4) + expect(inspectText(`aé€${ASTRAL}`).bytes).toBe(10) + }) + + it('reports lone surrogates as not well formed', () => { + expect(inspectText(ASTRAL).wellFormed).toBe(true) + expect(inspectText('\ud800').wellFormed).toBe(false) + expect(inspectText('\udc00').wellFormed).toBe(false) + expect(inspectText('a\ud800b').wellFormed).toBe(false) + }) + + it('reports NUL characters', () => { + expect(inspectText('a\u0000b').hasNul).toBe(true) + expect(inspectText('ab').hasNul).toBe(false) + }) +}) + +describe('normalizePollText', () => { + it('trims and composes to NFC', () => { + expect(normalizePollText(` cafe${COMBINING_ACUTE} `)).toBe('café') + }) +}) + +describe('getStatementIssue', () => { + it('accepts ordinary text', () => { + expect(getStatementIssue('Reposts should show who boosted them')).toBeNull() + }) + + it('treats blank text as empty', () => { + expect(getStatementIssue('')).toBe('empty') + expect(getStatementIssue(' \n ')).toBe('empty') + }) + + it('enforces the grapheme limit', () => { + expect( + getStatementIssue('a'.repeat(POLL_STATEMENT_MAX_GRAPHEMES)), + ).toBeNull() + expect( + getStatementIssue('a'.repeat(POLL_STATEMENT_MAX_GRAPHEMES + 1)), + ).toBe('too_long') + }) + + it('enforces the byte limit on its own', () => { + const cluster = '\u20ac\u20dd' + const fits = cluster.repeat(333) + expect(inspectText(fits).bytes).toBe(1998) + expect(getStatementIssue(fits)).toBeNull() + const over = cluster.repeat(334) + expect(inspectText(over).bytes).toBe(POLL_STATEMENT_MAX_BYTES + 4) + expect(over.length).toBe(668) + expect(countGraphemes(over)).toBe(334) + expect(getStatementIssue(over)).toBe('too_long') + }) + + it('enforces the character limit of the statement column on its own', () => { + const cluster = 'x\u0336\u0336' + const fits = cluster.repeat(332) + expect(fits.normalize('NFC').length).toBe(996) + expect(getStatementIssue(fits)).toBeNull() + const over = cluster.repeat(333) + expect(over.normalize('NFC').length).toBe(POLL_STATEMENT_MAX_CHARS + 2) + expect(inspectText(over).bytes).toBe(1665) + expect(countGraphemes(over)).toBe(333) + expect(getStatementIssue(over)).toBe('too_long') + }) + + it('rejects text that cannot be stored', () => { + expect(getStatementIssue('a\u0000b')).toBe('invalid') + expect(getStatementIssue('a\ud800b')).toBe('invalid') + }) +}) + +describe('getStatementIssues', () => { + it('marks the later of two equal statements as a duplicate', () => { + expect(getStatementIssues(['One', 'Two', 'One'])).toEqual([ + null, + null, + 'duplicate', + ]) + }) + + it('compares after trimming, composing and lower-casing', () => { + expect(getStatementIssues(['Café', ` cafe${COMBINING_ACUTE} `])).toEqual([ + null, + 'duplicate', + ]) + }) + + it('reports the statement problem before the duplicate', () => { + expect(getStatementIssues(['', ''])).toEqual(['empty', 'empty']) + }) +}) + +describe('isPollDraftPublishable', () => { + it('needs between one and ten valid, distinct statements', () => { + expect(isPollDraftPublishable({statements: ['One']})).toBe(true) + expect(isPollDraftPublishable({statements: []})).toBe(false) + expect(isPollDraftPublishable({statements: ['One', '']})).toBe(false) + expect(isPollDraftPublishable({statements: ['One', 'one']})).toBe(false) + const ten = Array.from(Array(POLL_MAX_STATEMENTS).keys(), i => `S${i}`) + expect(isPollDraftPublishable({statements: ten})).toBe(true) + expect(isPollDraftPublishable({statements: [...ten, 'S10']})).toBe(false) + }) +}) + +describe('pollStatementsForPublish', () => { + it('returns normalized statements in order', () => { + expect( + pollStatementsForPublish({statements: [' First ', 'Second']}), + ).toEqual(['First', 'Second']) + }) +}) + +describe('pollTopicFromText', () => { + it('uses short post text as it is, with whitespace collapsed', () => { + expect(pollTopicFromText(' What should we\n\nbuild next? ')).toBe( + 'What should we build next?', + ) + }) + + it('keeps text of exactly the limit', () => { + const text = 'a'.repeat(POLL_TOPIC_MAX_GRAPHEMES) + expect(pollTopicFromText(text)).toBe(text) + }) + + it('shortens longer text to the grapheme limit with a mark', () => { + const topic = pollTopicFromText('a'.repeat(POLL_TOPIC_MAX_GRAPHEMES + 1)) + expect(topic).toBe('a'.repeat(POLL_TOPIC_MAX_GRAPHEMES - 1) + '…') + expect(countGraphemes(topic)).toBe(POLL_TOPIC_MAX_GRAPHEMES) + }) + + it('shortens to the byte limit when that is reached first', () => { + const cluster = ASTRAL + '̀' + const text = cluster.repeat(POLL_TOPIC_MAX_GRAPHEMES) + expect(inspectText(text).bytes).toBe(1200) + const topic = pollTopicFromText(text) + expect(inspectText(topic).bytes).toBeLessThanOrEqual(POLL_TOPIC_MAX_BYTES) + expect(topic).toBe(cluster.repeat(166) + '…') + expect(inspectText(topic).bytes).toBe(999) + }) + + it('does not end on a space before the mark', () => { + const text = 'a'.repeat(198) + ' ' + 'b'.repeat(10) + expect(pollTopicFromText(text)).toBe('a'.repeat(198) + '…') + }) +}) + +describe('isPollTopicPublishable', () => { + it('needs text that can be stored', () => { + expect(isPollTopicPublishable('A question')).toBe(true) + expect(isPollTopicPublishable('')).toBe(false) + expect(isPollTopicPublishable(' \n ')).toBe(false) + expect(isPollTopicPublishable('a\u0000b')).toBe(false) + expect(isPollTopicPublishable('a\ud800b')).toBe(false) + }) +}) + +describe('decodePollDraft', () => { + const assembly = { + rkey: '3kaaaaaaaaaa2', + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: 'abc', + } + + it('keeps unfinished statements as typed', () => { + expect(decodePollDraft({statements: ['', ' a ']})).toEqual({ + statements: ['', ' a '], + assembly: undefined, + }) + }) + + it('restores an assembly reference', () => { + expect( + decodePollDraft({ + statements: ['a'], + assembly: {...assembly, conversationId: '7abcdefghi', reportId: 'r1'}, + }), + ).toEqual({ + statements: ['a'], + assembly: {...assembly, conversationId: '7abcdefghi', reportId: 'r1'}, + }) + }) + + it('drops a malformed assembly reference but keeps the statements', () => { + expect(decodePollDraft({statements: ['a'], assembly: {rkey: 1}})).toEqual({ + statements: ['a'], + assembly: undefined, + }) + expect( + decodePollDraft({ + statements: ['a'], + assembly: {...assembly, conversationId: 7}, + }), + ).toEqual({ + statements: ['a'], + assembly: {...assembly, conversationId: undefined, reportId: undefined}, + }) + }) + + it('rejects anything that is not a list of one to ten strings', () => { + expect(decodePollDraft(undefined)).toBeUndefined() + expect(decodePollDraft({statements: []})).toBeUndefined() + expect(decodePollDraft({statements: ['a', 1]})).toBeUndefined() + expect(decodePollDraft({statements: 'a'})).toBeUndefined() + expect( + decodePollDraft({ + statements: Array.from(Array(POLL_MAX_STATEMENTS + 1).keys(), String), + }), + ).toBeUndefined() + }) +}) diff --git a/src/lib/api/__tests__/space-post-poll.test.ts b/src/lib/api/__tests__/space-post-poll.test.ts new file mode 100644 index 000000000..7fe7bf61c --- /dev/null +++ b/src/lib/api/__tests__/space-post-poll.test.ts @@ -0,0 +1,45 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {resolveEmbed, resolveRT} from '../index' +import {postToSpace} from '../space-post' +import {spaceCreateRecord} from '../space-write' + +jest.mock('../index', () => ({ + quotedSpace: jest.fn(() => null), + resolveEmbed: jest.fn(), + resolveReply: jest.fn(), + resolveRT: jest.fn(), +})) +jest.mock('../space-write', () => ({ + POST_COLLECTION: 'app.bsky.feed.post', + spaceCreateRecord: jest.fn(), +})) + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +const draft = (embed: Record) => ({ + richtext: {text: 'hi', facets: []}, + shortenedGraphemeLength: 2, + labels: [], + embed, +}) + +describe('posting a thread into a space', () => { + it('refuses the whole thread before the first write when any post has a poll', async () => { + await expect( + postToSpace({} as AtpAgent, {} as QueryClient, SPACE, { + thread: { + posts: [draft({}), draft({poll: {statements: ['A']}})], + postgate: {}, + threadgate: [], + blackskyOnly: false, + } as never, + }), + ).rejects.toThrow(/Polls are not available/) + + expect(resolveRT).not.toHaveBeenCalled() + expect(resolveEmbed).not.toHaveBeenCalled() + expect(spaceCreateRecord).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/api/assembly.ts b/src/lib/api/assembly.ts new file mode 100644 index 000000000..6ade11e29 --- /dev/null +++ b/src/lib/api/assembly.ts @@ -0,0 +1,287 @@ +import {type AtpAgent} from '@atproto/api' +import {TID} from '@atproto/common-web' + +import {type AssemblyRef, normalizePollText} from '#/lib/api/poll' +import {isNetworkError} from '#/lib/strings/errors' +import {ASSEMBLY_SERVICE_DID, ASSEMBLY_URL} from '#/env' +import {getServiceAuthToken} from './service-auth' + +export const ASSEMBLY_CONVERSATION_COLLECTION = + 'community.blacksky.assembly.conversation' +export const ASSEMBLY_CREATE_LXM = + 'community.blacksky.assembly.createConversation' + +const CREATE_TIMEOUT_MS = 30e3 +const CREATE_RETRIES = 2 +const CREATE_RETRY_PAUSE_MS = 1e3 +const TOKEN_LIFETIME_SECONDS = 60 +const RECORDS_INCOMPLETE = 'polis_err_atproto_statement_records_incomplete' +const UNSUPPORTED_ACCOUNT = 'polis_err_atproto_unsupported_did' +const RATE_LIMITED = 'polis_err_atproto_conversation_rate_limited' + +export type AssemblyErrorCode = + | 'not_eligible' + | 'quota' + | 'busy' + | 'invalid' + | 'conflict' + | 'removed' + | 'unavailable' + | 'auth' + | 'network' + +export type AssemblyErrorStage = 'record' | 'token' | 'create' + +export class AssemblyError extends Error { + readonly code: AssemblyErrorCode + readonly stage: AssemblyErrorStage + + constructor(code: AssemblyErrorCode, stage: AssemblyErrorStage) { + super(code) + this.name = 'AssemblyError' + this.code = code + this.stage = stage + } +} + +const REFUSALS: Record = { + 400: 'invalid', + 403: 'not_eligible', + 409: 'conflict', + 410: 'removed', + 429: 'quota', +} + +type CreateResponse = {status: number; data: Record} + +function assemblyOrigin(): string { + return ASSEMBLY_URL.replace(/\/+$/, '') +} + +export function assemblyFingerprint( + topic: string, + statements: string[], +): string { + return JSON.stringify([ + normalizePollText(topic), + statements.map(normalizePollText), + ]) +} + +export function assemblyUrl(conversationId: string): string { + return `${assemblyOrigin()}/${encodeURIComponent(conversationId)}` +} + +export function assemblyReportUrl(reportId: string): string { + return `${assemblyOrigin()}/report/${encodeURIComponent(reportId)}` +} + +export function assemblyThumbUrl(conversationId: string): string { + return `${assemblyOrigin()}/api/v3/og-image/${encodeURIComponent(conversationId)}` +} + +export function isAssemblyConversationId(value: unknown): value is string { + return typeof value === 'string' && /^[0-9][0-9A-Za-z]{4,}$/.test(value) +} + +export function buildAssemblyExternal(input: { + conversationId: string + topic: string + statements: string[] +}): {uri: string; title: string; description: string} { + return { + uri: assemblyUrl(input.conversationId), + title: input.topic, + description: input.statements + .map((statement, i) => `${i + 1}. ${statement}`) + .join('\n'), + } +} + +function wait(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +function parseBody(text: string): Record { + try { + const value: unknown = JSON.parse(text) + if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + return value as Record + } + } catch {} + return {} +} + +async function removeRecord(agent: AtpAgent, rkey: string): Promise { + try { + await agent.com.atproto.repo.deleteRecord({ + repo: agent.assertDid, + collection: ASSEMBLY_CONVERSATION_COLLECTION, + rkey, + }) + } catch {} +} + +async function writeRecord( + agent: AtpAgent, + ref: AssemblyRef, + topic: string, + staleRkey: string | undefined, +): Promise<{uri: string; cid: string}> { + try { + if (staleRkey) await removeRecord(agent, staleRkey) + const {data} = await agent.com.atproto.repo.putRecord({ + repo: agent.assertDid, + collection: ASSEMBLY_CONVERSATION_COLLECTION, + rkey: ref.rkey, + record: { + $type: ASSEMBLY_CONVERSATION_COLLECTION, + topic, + authRequired: true, + createdAt: ref.createdAt, + }, + }) + return {uri: data.uri, cid: data.cid} + } catch (e) { + throw new AssemblyError( + isNetworkError(e) ? 'network' : 'unavailable', + 'record', + ) + } +} + +async function requestCreate( + agent: AtpAgent, + body: string, +): Promise { + let token: string + try { + token = await getServiceAuthToken({ + agent, + aud: ASSEMBLY_SERVICE_DID, + lxm: ASSEMBLY_CREATE_LXM, + exp: Math.floor(Date.now() / 1000) + TOKEN_LIFETIME_SECONDS, + }) + } catch (e) { + throw new AssemblyError(isNetworkError(e) ? 'network' : 'auth', 'token') + } + + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), CREATE_TIMEOUT_MS) + try { + const response = await fetch( + `${assemblyOrigin()}/api/v3/atproto/conversations`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body, + signal: controller.signal, + }, + ) + return {status: response.status, data: parseBody(await response.text())} + } catch { + throw new AssemblyError('network', 'create') + } finally { + clearTimeout(timer) + } +} + +export async function ensureAssembly( + agent: AtpAgent, + input: { + topic: string + statements: string[] + ref?: AssemblyRef + onRef: (ref: AssemblyRef) => void + }, + {pause = wait}: {pause?: (ms: number) => Promise} = {}, +): Promise<{ref: AssemblyRef & {conversationId: string}; isReplay: boolean}> { + const topic = normalizePollText(input.topic) + const statements = input.statements.map(normalizePollText) + const fingerprint = assemblyFingerprint(topic, statements) + const previous = input.ref + const isUnchanged = previous?.fingerprint === fingerprint + + if ( + previous && + isUnchanged && + isAssemblyConversationId(previous.conversationId) + ) { + return { + ref: {...previous, conversationId: previous.conversationId}, + isReplay: true, + } + } + + const ref: AssemblyRef = + previous && isUnchanged + ? {rkey: previous.rkey, createdAt: previous.createdAt, fingerprint} + : {rkey: TID.nextStr(), createdAt: new Date().toISOString(), fingerprint} + input.onRef(ref) + + const staleRkey = + previous && !isUnchanged && !previous.conversationId + ? previous.rkey + : undefined + const record = await writeRecord(agent, ref, topic, staleRkey) + const body = JSON.stringify({ + topic, + statements, + conversation: {at_uri: record.uri, at_cid: record.cid}, + }) + + let response = await requestCreate(agent, body) + for ( + let retries = 0; + retries < CREATE_RETRIES && + response.status === 503 && + response.data.error === RECORDS_INCOMPLETE; + retries++ + ) { + await pause(CREATE_RETRY_PAUSE_MS) + response = await requestCreate(agent, body) + } + + if (response.status === 200 || response.status === 201) { + const {conversation_id, report_id, created} = response.data + if (!isAssemblyConversationId(conversation_id)) { + throw new AssemblyError('unavailable', 'create') + } + const createdRef = { + ...ref, + conversationId: conversation_id, + ...(typeof report_id === 'string' && report_id + ? {reportId: report_id} + : {}), + } + input.onRef(createdRef) + return {ref: createdRef, isReplay: created === false} + } + + if (response.status === 429 && response.data.error === RATE_LIMITED) { + throw new AssemblyError('busy', 'create') + } + + const refusal = REFUSALS[response.status] + if (refusal) { + await removeRecord(agent, ref.rkey) + if (refusal === 'conflict') { + input.onRef({ + rkey: TID.nextStr(), + createdAt: new Date().toISOString(), + fingerprint, + }) + } + throw new AssemblyError( + response.data.error === UNSUPPORTED_ACCOUNT ? 'not_eligible' : refusal, + 'create', + ) + } + throw new AssemblyError( + response.status === 401 ? 'auth' : 'unavailable', + 'create', + ) +} diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 8a1f279e2..ea95a18cd 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -25,6 +25,11 @@ import {sha256} from 'js-sha256' import {CID} from 'multiformats/cid' import * as Hasher from 'multiformats/hashes/hasher' +import { + assemblyThumbUrl, + buildAssemblyExternal, + ensureAssembly, +} from '#/lib/api/assembly' import {communityXrpc} from '#/lib/api/community' import { admitFeedPost, @@ -32,6 +37,13 @@ import { isSpaceBackedFeed, } from '#/lib/api/community-feed' import {fetchCommunityPostView} from '#/lib/api/community-post' +import { + type AssemblyRef, + type PollDraft, + pollStatementsForPublish, + pollTopicFromText, +} from '#/lib/api/poll' +import {imageToThumb} from '#/lib/api/resolve' import {spaceOfPostUrl} from '#/lib/api/space-permalink' import {postToSpace} from '#/lib/api/space-post' import {isSpaceRecordUri, spaceOfRecordUri} from '#/lib/api/space-uri' @@ -60,6 +72,7 @@ import {uploadBlob} from './upload-blob' export {uploadBlob} const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' +const ASSEMBLY_THUMB_TIMEOUT_MS = 5e3 /** * The space a quote belongs to, whichever form it is in — a pasted permalink @@ -80,19 +93,57 @@ function embedNamesSpaceRecord(embed: unknown): boolean { return typeof uri === 'string' && isSpaceRecordUri(uri) } +function refusePoll(thread: ThreadDraft) { + if (thread.posts.some(p => p.embed.poll)) { + throw new Error(t`Polls are only available on public posts.`) + } +} + +function refusePollWithAttachments(draft: PostDraft) { + if ( + draft.embed.poll && + (draft.embed.media || draft.embed.link || draft.embed.quote) + ) { + throw new Error( + t`A poll cannot be combined with media, a link card or a quote.`, + ) + } +} + +function findPollPost(thread: ThreadDraft): PostDraft | undefined { + const [pollPost, ...others] = thread.posts.filter(p => p.embed.poll) + if (others.length) { + throw new Error(t`A thread can only have one poll.`) + } + if (pollPost) { + refusePollWithAttachments(pollPost) + } + return pollPost +} + export interface PostOpts { thread: ThreadDraft draftId?: string replyTo?: string onStateChange?: (state: string) => void + onAssembly?: (postId: string, ref: AssemblyRef) => void langs?: string[] } +export type PostResult = { + uris: string[] + assembly?: { + conversationId: string + statementCount: number + isReplay: boolean + } +} + export async function post( agent: AtpAgent, queryClient: QueryClient, opts: PostOpts, -) { +): Promise { let thread = opts.thread const replySpace = spaceOfRecordUri(opts.replyTo) // Replying to or quoting a space post: the parent's space is the target, and @@ -108,6 +159,7 @@ export async function post( t`This reply targets a different private space than its parent.`, ) } + refusePoll(thread) return postToSpace(agent, queryClient, space, opts) } @@ -131,6 +183,7 @@ export async function post( // the community routing below, which would otherwise claim it. const config = thread.communityFeed?.config if (isSpaceBackedFeed(config)) { + refusePoll(thread) return postToSpace(agent, queryClient, config.space, opts) } @@ -163,6 +216,7 @@ export async function post( isReplyToCommunityPost || isQuoteOfCommunityPost ) { + refusePoll(thread) return postCommunity(agent, queryClient, opts) } @@ -181,6 +235,8 @@ export async function post( throw new Error('Public posts cannot embed a community post') } + const pollPost = findPollPost(thread) + let replyPromise: | Promise | AppBskyFeedPost.Record['reply'] @@ -190,6 +246,35 @@ export async function post( replyPromise = resolveReply(agent, opts.replyTo) } + let assembly: PostResult['assembly'] + const poll = pollPost?.embed.poll + if (pollPost && poll) { + // An assembly is public and cannot be withdrawn, so a reply whose parent + // is gone has to fail before one is started. + await replyPromise + opts.onStateChange?.(t`Starting poll...`) + const statements = pollStatementsForPublish(poll) + const {ref, isReplay} = await ensureAssembly(agent, { + topic: pollTopicFromText(pollPost.richtext.text), + statements, + ref: poll.assembly, + onRef: next => opts.onAssembly?.(pollPost.id, next), + }) + assembly = { + conversationId: ref.conversationId, + statementCount: statements.length, + isReplay, + } + thread = { + ...thread, + posts: thread.posts.map(p => + p === pollPost + ? {...p, embed: {...p.embed, poll: {...poll, assembly: ref}}} + : p, + ), + } + } + // add top 3 languages from user preferences if langs is provided let langs = opts.langs if (opts.langs) { @@ -325,7 +410,7 @@ export async function post( ) } - return {uris} + return {uris, assembly} } async function postCommunity( @@ -713,6 +798,9 @@ export async function resolveEmbed( | $Typed | undefined > { + if (draft.embed.poll) { + return resolveAssembly(agent, draft, draft.embed.poll, onStateChange) + } if (draft.embed.quote) { const [resolvedMedia, resolvedQuote] = await Promise.all([ resolveMedia(agent, queryClient, draft.embed, onStateChange), @@ -758,6 +846,58 @@ export async function resolveEmbed( return undefined } +async function resolveAssembly( + agent: AtpAgent, + draft: PostDraft, + poll: PollDraft, + onStateChange: ((state: string) => void) | undefined, +): Promise<$Typed> { + refusePollWithAttachments(draft) + const conversationId = poll.assembly?.conversationId + if (!conversationId) { + throw new Error('A poll cannot be posted before its assembly exists') + } + return { + $type: 'app.bsky.embed.external', + external: { + ...buildAssemblyExternal({ + conversationId, + topic: pollTopicFromText(draft.richtext.text), + statements: pollStatementsForPublish(poll), + }), + thumb: await uploadAssemblyThumb(agent, conversationId, onStateChange), + }, + } +} + +async function uploadAssemblyThumb( + agent: AtpAgent, + conversationId: string, + onStateChange: ((state: string) => void) | undefined, +): Promise { + let timer: ReturnType | undefined + try { + const thumb = await Promise.race([ + imageToThumb(assemblyThumbUrl(conversationId)), + new Promise(resolve => { + timer = setTimeout(() => resolve(undefined), ASSEMBLY_THUMB_TIMEOUT_MS) + }), + ]) + if (!thumb) throw new Error('The image could not be read in time') + onStateChange?.(t`Uploading link thumbnail...`) + const {path, mime} = thumb.source + const response = await uploadBlob(agent, path, mime) + return response.data.blob + } catch (e) { + logger.warn(`Failed to attach the poll thumbnail`, { + safeMessage: e instanceof Error ? e.message : String(e), + }) + return undefined + } finally { + clearTimeout(timer) + } +} + async function resolveMedia( agent: AtpAgent, queryClient: QueryClient, diff --git a/src/lib/api/poll.ts b/src/lib/api/poll.ts new file mode 100644 index 000000000..a07924bf9 --- /dev/null +++ b/src/lib/api/poll.ts @@ -0,0 +1,179 @@ +import {countGraphemes, graphemeSegments} from 'unicode-segmenter/grapheme' + +export const POLL_MAX_STATEMENTS = 10 +export const POLL_STATEMENT_MAX_GRAPHEMES = 400 +export const POLL_STATEMENT_MAX_BYTES = 2000 +export const POLL_STATEMENT_MAX_CHARS = 997 +export const POLL_TOPIC_MAX_GRAPHEMES = 200 +export const POLL_TOPIC_MAX_BYTES = 1000 + +export const POLL_VOTE_VALUES = ['agree', 'disagree', 'pass'] as const +export type PollVoteValue = (typeof POLL_VOTE_VALUES)[number] + +export type AssemblyRef = { + rkey: string + createdAt: string + fingerprint: string + conversationId?: string + reportId?: string +} + +export type PollDraft = { + statements: string[] + assembly?: AssemblyRef +} + +export type PollStatementIssue = 'empty' | 'too_long' | 'invalid' | 'duplicate' + +const TRUNCATION_MARK = '…' + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v) +} + +export function inspectText(text: string): { + bytes: number + wellFormed: boolean + hasNul: boolean +} { + let bytes = 0 + let wellFormed = true + let hasNul = false + for (let i = 0; i < text.length; i++) { + const unit = text.charCodeAt(i) + if (unit === 0) hasNul = true + if (unit < 0x80) { + bytes += 1 + } else if (unit < 0x800) { + bytes += 2 + } else if (unit >= 0xd800 && unit <= 0xdbff) { + const next = text.charCodeAt(i + 1) + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4 + i++ + } else { + wellFormed = false + bytes += 3 + } + } else if (unit >= 0xdc00 && unit <= 0xdfff) { + wellFormed = false + bytes += 3 + } else { + bytes += 3 + } + } + return {bytes, wellFormed, hasNul} +} + +export function normalizePollText(text: string): string { + return text.trim().normalize('NFC') +} + +export function getStatementIssue(text: string): PollStatementIssue | null { + const statement = normalizePollText(text) + if (statement.length === 0) return 'empty' + const {bytes, wellFormed, hasNul} = inspectText(statement) + if (!wellFormed || hasNul) return 'invalid' + if ( + bytes > POLL_STATEMENT_MAX_BYTES || + statement.length > POLL_STATEMENT_MAX_CHARS || + countGraphemes(statement) > POLL_STATEMENT_MAX_GRAPHEMES + ) { + return 'too_long' + } + return null +} + +export function getStatementIssues( + statements: string[], +): (PollStatementIssue | null)[] { + const seen = new Set() + return statements.map(text => { + const issue = getStatementIssue(text) + if (issue) return issue + const key = normalizePollText(text).toLowerCase() + if (seen.has(key)) return 'duplicate' + seen.add(key) + return null + }) +} + +export function isPollDraftPublishable(draft: PollDraft): boolean { + return ( + draft.statements.length >= 1 && + draft.statements.length <= POLL_MAX_STATEMENTS && + getStatementIssues(draft.statements).every(issue => issue === null) + ) +} + +export function pollStatementsForPublish(draft: PollDraft): string[] { + return draft.statements.map(normalizePollText) +} + +export function pollTopicFromText(text: string): string { + const topic = normalizePollText(text).replace(/\s+/g, ' ') + if ( + countGraphemes(topic) <= POLL_TOPIC_MAX_GRAPHEMES && + inspectText(topic).bytes <= POLL_TOPIC_MAX_BYTES + ) { + return topic + } + const markBytes = inspectText(TRUNCATION_MARK).bytes + let kept = '' + let graphemes = 0 + let bytes = 0 + for (const {segment} of graphemeSegments(topic)) { + const segmentBytes = inspectText(segment).bytes + if ( + graphemes + 1 > POLL_TOPIC_MAX_GRAPHEMES - 1 || + bytes + segmentBytes > POLL_TOPIC_MAX_BYTES - markBytes + ) { + break + } + kept += segment + graphemes += 1 + bytes += segmentBytes + } + return kept.trimEnd() + TRUNCATION_MARK +} + +export function isPollTopicPublishable(text: string): boolean { + const topic = pollTopicFromText(text) + if (topic.length === 0 || topic === TRUNCATION_MARK) return false + const {wellFormed, hasNul} = inspectText(topic) + return wellFormed && !hasNul +} + +function decodeAssemblyRef(value: unknown): AssemblyRef | undefined { + if (!isObject(value)) return undefined + const {rkey, createdAt, fingerprint, conversationId, reportId} = value + if ( + typeof rkey !== 'string' || + typeof createdAt !== 'string' || + typeof fingerprint !== 'string' + ) { + return undefined + } + return { + rkey, + createdAt, + fingerprint, + conversationId: + typeof conversationId === 'string' ? conversationId : undefined, + reportId: typeof reportId === 'string' ? reportId : undefined, + } +} + +export function decodePollDraft(value: unknown): PollDraft | undefined { + if (!isObject(value)) return undefined + const {statements, assembly} = value + if ( + !Array.isArray(statements) || + statements.length < 1 || + statements.length > POLL_MAX_STATEMENTS || + !statements.every(s => typeof s === 'string') + ) { + return undefined + } + return {statements, assembly: decodeAssemblyRef(assembly)} +} diff --git a/src/lib/api/space-post.ts b/src/lib/api/space-post.ts index 5bb964621..a7cb079c4 100644 --- a/src/lib/api/space-post.ts +++ b/src/lib/api/space-post.ts @@ -48,6 +48,12 @@ export async function postToSpace( ) } + // Posts are written one at a time, so an unsupported draft has to be refused + // before the first write rather than part-way through the thread. + if (thread.posts.some(p => p.embed.poll)) { + throw new Error(t`Polls are not available in private community feeds.`) + } + // Threads are written in order: each reply refers to the space URI the host // returned for the post before it, so they cannot be batched. let root: {uri: string; cid: string} | undefined diff --git a/src/lib/strings/embed-player.ts b/src/lib/strings/embed-player.ts index 53122cc02..4a6451654 100644 --- a/src/lib/strings/embed-player.ts +++ b/src/lib/strings/embed-player.ts @@ -1,6 +1,6 @@ import {Dimensions} from 'react-native' -import {IS_WEB} from '#/env' +import {ASSEMBLY_URL, IS_WEB} from '#/env' import { parseStreamplaceActor, STREAMPLACE_ORIGIN, @@ -108,6 +108,27 @@ export interface EmbedPlayerParams { const giphyRegex = /media(?:[0-4]\.giphy\.com|\.giphy\.com)/i const gifFilenameRegex = /^(\S+)\.(webp|gif|mp4)$/i +const ASSEMBLY_HOSTNAME = 'assembly.blacksky.community' +const ASSEMBLY_HOST = parseHost(ASSEMBLY_URL) + +function parseHost(url: string): string | undefined { + try { + return new URL(url).host || undefined + } catch { + return undefined + } +} + +function getAssemblyOrigin(urlp: URL): string | undefined { + if (urlp.hostname === ASSEMBLY_HOSTNAME) { + return `https://${ASSEMBLY_HOSTNAME}` + } + if (ASSEMBLY_HOST && urlp.host === ASSEMBLY_HOST) { + return ASSEMBLY_URL.replace(/\/+$/, '') + } + return undefined +} + export function parseEmbedPlayerFromUrl( url: string, ): EmbedPlayerParams | undefined { @@ -515,13 +536,14 @@ export function parseEmbedPlayerFromUrl( } // Assembly conversations - if (urlp.hostname === 'assembly.blacksky.community') { + const assemblyOrigin = getAssemblyOrigin(urlp) + if (assemblyOrigin) { const match = urlp.pathname.match(/^\/([0-9A-Za-z]{5,})$/) if (match) { return { type: 'assembly_conversation' as EmbedPlayerType, source: 'assembly' as EmbedPlayerSource, - playerUri: `https://assembly.blacksky.community/${match[1]}`, + playerUri: `${assemblyOrigin}/${match[1]}`, hideDetails: false, } } diff --git a/src/lib/strings/rich-text-manip.ts b/src/lib/strings/rich-text-manip.ts index 099fbffb0..0addcc664 100644 --- a/src/lib/strings/rich-text-manip.ts +++ b/src/lib/strings/rich-text-manip.ts @@ -32,6 +32,28 @@ export function shortenLinks(rt: RichText): RichText { return rt } +export function expandLinks(rt: RichText): RichText { + if (!rt.facets?.length) { + return rt + } + rt = rt.clone() + if (rt.facets) { + for (const facet of rt.facets) { + const link = facet.features.find(AppBskyRichtextFacet.isLink) + if (!link) { + continue + } + const {byteStart, byteEnd} = facet.index + const full = new UnicodeString(link.uri) + rt.insert(byteStart, full.utf16) + facet.index.byteStart = byteStart + facet.index.byteEnd = byteStart + full.length + rt.delete(byteStart + full.length, byteEnd + full.length) + } + } + return rt +} + // filter out any mention facets that didn't map to a user export function stripInvalidMentions(rt: RichText): RichText { if (!rt.facets?.length) { diff --git a/src/state/queries/nuxs/definitions.ts b/src/state/queries/nuxs/definitions.ts index 7f88c4bea..2c0e6b976 100644 --- a/src/state/queries/nuxs/definitions.ts +++ b/src/state/queries/nuxs/definitions.ts @@ -17,6 +17,7 @@ export enum Nux { DraftsAnnouncement = 'DraftsAnnouncement', GroupChatsAnnouncement = 'GroupChatsAnnouncement', InviteFriendsAnnouncement = 'InviteFriendsAnnouncement', + ComposerPoll = 'ComposerPoll', } export const nuxNames = new Set(Object.values(Nux)) @@ -78,6 +79,10 @@ export type AppNux = BaseNux< id: Nux.InviteFriendsAnnouncement data: undefined } + | { + id: Nux.ComposerPoll + data: undefined + } > export const NuxSchemas: Record | undefined> = { @@ -95,4 +100,5 @@ export const NuxSchemas: Record | undefined> = { [Nux.DraftsAnnouncement]: undefined, [Nux.GroupChatsAnnouncement]: undefined, [Nux.InviteFriendsAnnouncement]: undefined, + [Nux.ComposerPoll]: undefined, } diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 4fdf5fad2..607b3a2bb 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -60,6 +60,7 @@ import {Trans, useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' import {useQueries, useQueryClient} from '@tanstack/react-query' +import {AssemblyError, type AssemblyErrorCode} from '#/lib/api/assembly' import { type CommunityFeedTarget, isSpaceBackedFeed, @@ -69,6 +70,7 @@ import { isCommunityPostUri, } from '#/lib/api/community-post' import * as apilib from '#/lib/api/index' +import {type AssemblyRef} from '#/lib/api/poll' import {EmbeddingDisabledError} from '#/lib/api/resolve' import { isSpaceRecordUri, @@ -134,6 +136,8 @@ import {LabelsBtn} from '#/view/com/composer/labels/LabelsBtn' import {Gallery} from '#/view/com/composer/photos/Gallery' import {OpenCameraBtn} from '#/view/com/composer/photos/OpenCameraBtn' import {SelectGifBtn} from '#/view/com/composer/photos/SelectGifBtn' +import {PollEditor} from '#/view/com/composer/poll/PollEditor' +import {SelectPollBtn} from '#/view/com/composer/poll/SelectPollBtn' import {PostTargetControls} from '#/view/com/composer/PostTargetControls' import {SuggestedLanguage} from '#/view/com/composer/select-language/SuggestedLanguage' // TODO: Prevent naming components that coincide with RN primitives @@ -161,6 +165,7 @@ import {Text} from '#/components/Typography' import {useAnalytics} from '#/analytics' import { IS_ANDROID, + IS_DEV, IS_IOS, IS_LIQUID_GLASS, IS_NATIVE, @@ -192,10 +197,14 @@ import { composerReducer, createComposerState, type EmbedDraft, + isPollAllowed, + isPollPostable, MAX_GALLERY_IMAGES, type PostAction, type PostDraft, + postHasAttachment, type ThreadDraft, + threadHasPoll, } from './state/composer' import { NO_VIDEO, @@ -808,7 +817,8 @@ export const ComposePost = ({ post => post.richtext.text.trim().length > 0 || post.embed.media || - post.embed.link, + post.embed.link || + post.embed.poll, ) ax.metric('draft:discard', { logContext: 'ComposerClose', @@ -832,6 +842,7 @@ export const ComposePost = ({ if (firstPost.embed.quote) return false // Has link if (firstPost.embed.link) return false + if (firstPost.embed.poll) return false return true }, [thread.posts]) @@ -868,7 +879,10 @@ export const ComposePost = ({ const hasContent = thread.posts.some( post => - post.shortenedGraphemeLength > 0 || post.embed.media || post.embed.link, + post.shortenedGraphemeLength > 0 || + post.embed.media || + post.embed.link || + post.embed.poll, ) // Show discard prompt if there's content AND either: @@ -957,6 +971,33 @@ export const ComposePost = ({ !ChatBskyGroupDefs.isJoinLinkPreviewView(q.data.view), ) + const canAddPoll = + isPollAllowed(thread, replyTo?.uri) && !threadHasPoll(thread) + + const getAssemblyErrorMessage = useCallback( + (code: AssemblyErrorCode): string => { + switch (code) { + case 'not_eligible': + return l`Polls are not available for your account yet.` + case 'quota': + return l`You have started the maximum number of polls for today. Try again tomorrow.` + case 'busy': + return l`People's Assembly is busy. Wait a few seconds and post again.` + case 'invalid': + return l`This poll could not be created. Check the statements and try again.` + case 'conflict': + return l`This poll changed while it was being created. Please try again.` + case 'removed': + return l`This poll was removed and cannot be posted.` + case 'auth': + case 'network': + case 'unavailable': + return l`Could not reach People's Assembly. Your post was not sent.` + } + }, + [l], + ) + const canPost = !missingAltError && !hasUnavailableChatInvite && @@ -968,7 +1009,8 @@ export const ComposePost = ({ !( post.embed.media?.type === 'video' && post.embed.media.video.status === 'error' - )), + ) && + isPollPostable(post)), ) const getFilteredThread = useCallback((): { @@ -1037,15 +1079,28 @@ export const ComposePost = ({ let postSuccessData: OnPostSuccessData try { logger.info(`composer: posting...`) - postUri = ( - await apilib.post(agent, queryClient, { - thread: filteredThread, - draftId: composerState.draftId, - replyTo: replyTo?.uri, - onStateChange: setPublishingStage, - langs: currentLanguages, + const result = await apilib.post(agent, queryClient, { + thread: filteredThread, + draftId: composerState.draftId, + replyTo: replyTo?.uri, + onStateChange: setPublishingStage, + onAssembly: (postId: string, assembly: AssemblyRef) => { + composerDispatch({ + type: 'update_post', + postId, + postAction: {type: 'embed_set_poll_assembly', assembly}, + }) + }, + langs: currentLanguages, + }) + postUri = result.uris[0] + if (result.assembly) { + ax.metric('assembly:create', { + conversationId: result.assembly.conversationId, + statementCount: result.assembly.statementCount, + isReplay: result.assembly.isReplay, }) - ).uris[0] + } /* * Wait for app view to have received the post(s). If this fails, it's @@ -1107,6 +1162,9 @@ export const ComposePost = ({ err = l`We're sorry! The post you are replying to has been deleted.` } else if (e instanceof EmbeddingDisabledError) { err = l`This post's author has disabled quote posts.` + } else if (e instanceof AssemblyError) { + err = getAssemblyErrorMessage(e.code) + ax.metric('assembly:create:error', {stage: e.stage, code: e.code}) } else if (e instanceof SpaceUnsupportedError) { err = l`Your account is hosted elsewhere, so it cannot post to a private community feed. You can read it, but posting needs an account hosted here.` setNeedsMigration(true) @@ -1128,6 +1186,8 @@ export const ComposePost = ({ isPartOfThread: filteredThread.posts.length > 1, hasLink: !!post.embed.link, hasQuote: !!post.embed.quote, + hasPoll: !!post.embed.poll, + pollStatementCount: post.embed.poll?.statements.length ?? 0, langs: fromPostLanguages(currentLanguages), logContext: 'Composer', }) @@ -1274,6 +1334,7 @@ export const ComposePost = ({ loadedDraftCreatedAt, emptyPostsPromptControl, getFilteredThread, + getAssemblyErrorMessage, linkQueries, ]) @@ -1395,6 +1456,7 @@ export const ComposePost = ({ { + if (hasPoll) { + if (IS_WEB) { + Toast.show(l`Remove the poll to add media`, {type: 'warning'}) + } + return + } if ( uri.startsWith('data:video/') || (IS_WEB && uri.startsWith('data:image/gif')) @@ -1674,7 +1743,7 @@ let ComposerPost = memo(function ComposerPost({ onImageAdd([res]) } }, - [post.id, onSelectVideo, onImageAdd, l], + [post.id, hasPoll, onSelectVideo, onImageAdd, l], ) useHideKeyboardOnBackground() @@ -1739,12 +1808,7 @@ let ComposerPost = memo(function ComposerPost({ shape="round" style={[a.absolute, {top: 0, right: 0}]} onPress={() => { - if ( - post.shortenedGraphemeLength > 0 || - post.embed.media || - post.embed.link || - post.embed.quote - ) { + if (post.shortenedGraphemeLength > 0 || postHasAttachment(post)) { discardPromptControl.open() } else { dispatch({ @@ -1774,6 +1838,7 @@ let ComposerPost = memo(function ComposerPost({ onClearVideo(post.id)} isActivePost={isActive} @@ -1935,12 +2000,14 @@ function AltTextReminder({error}: {error: string}) { function ComposerEmbeds({ embed, + text, dispatch, clearVideo, canRemoveQuote, isActivePost, }: { embed: EmbedDraft + text: string dispatch: (action: PostAction) => void clearVideo: () => void canRemoveQuote: boolean @@ -1969,6 +2036,10 @@ function ComposerEmbeds({ )} + {embed.poll && ( + + )} + {!embed.media && embed.link && ( void + canAddPoll: boolean showAddButton: boolean onError: (error: string) => void onSelectVideo: (postId: string, asset: ImagePickerAsset) => void @@ -2161,6 +2234,9 @@ function ComposerFooter({ const t = useTheme() const {t: l} = useLingui() const {gtPhone} = useBreakpoints() + const ax = useAnalytics() + const arePollsEnabled = IS_DEV || ax.features.enabled(ax.features.PollsEnable) + const hasPoll = !!post.embed.poll /* * Once we've allowed a certain type of asset to be selected, we don't allow * other types of media to be selected. @@ -2188,6 +2264,9 @@ function ComposerFooter({ } else { isMediaSelectionDisabled = !!media } + if (hasPoll) { + isMediaSelectionDisabled = true + } const onImageAdd = useAddImagesWithCap(images.length, dispatch) @@ -2273,13 +2352,23 @@ function ComposerFooter({ /> - + + {arePollsEnabled && ( + dispatch({type: 'embed_add_poll'})} + disabled={!canAddPoll || postHasAttachment(post)} + /> + )} {IS_WEB && gtPhone ? ( @@ -2502,12 +2591,7 @@ async function whenAppViewReady( } function isEmptyPost(post: PostDraft) { - return ( - post.richtext.text.trim().length === 0 && - !post.embed.media && - !post.embed.link && - !post.embed.quote - ) + return post.richtext.text.trim().length === 0 && !postHasAttachment(post) } function useHideKeyboardOnBackground() { diff --git a/src/view/com/composer/PostTargetControls.tsx b/src/view/com/composer/PostTargetControls.tsx index 5866896c3..ea1541d82 100644 --- a/src/view/com/composer/PostTargetControls.tsx +++ b/src/view/com/composer/PostTargetControls.tsx @@ -3,10 +3,13 @@ import {Trans, useLingui} from '@lingui/react/macro' import {type CommunityFeedTarget} from '#/lib/api/community-feed' import { type ComposerAction, + isPublicTarget, type ThreadDraft, + threadHasPoll, } from '#/view/com/composer/state/composer' import {atoms as a} from '#/alf' import * as Toggle from '#/components/forms/Toggle' +import * as Toast from '#/components/Toast' export function PostTargetControls({ thread, @@ -37,6 +40,13 @@ export function PostTargetControls({ isCommunityMember && !(isReply && !isForcedBlackskyOnly) && (!isForcedCommunityTarget || isForcedBlackskyOnly) + const hasPoll = threadHasPoll(thread) + const announcePollRemoval = () => { + Toast.show( + t`Polls are only available on public posts, so the poll was removed.`, + {type: 'info'}, + ) + } return ( <> @@ -48,6 +58,9 @@ export function PostTargetControls({ disabled={isForcedBlackskyOnly || homeAppviewOutage} onChange={() => { const next = !thread.blackskyOnly + if (next && hasPoll) { + announcePollRemoval() + } dispatch({type: 'toggle_blacksky_only'}) setBlackskyOnlyDefault(next) }} @@ -70,13 +83,23 @@ export function PostTargetControls({ thread.communityFeed?.feed === contextualCommunityFeedTarget.feed } onChange={() => { + const isLeaving = + thread.communityFeed?.feed === contextualCommunityFeedTarget.feed + if ( + !isLeaving && + hasPoll && + !isPublicTarget({ + ...thread, + blackskyOnly: false, + communityFeed: contextualCommunityFeedTarget, + communityFeedUri: contextualCommunityFeedTarget.feed, + }) + ) { + announcePollRemoval() + } dispatch({ type: 'set_post_target', - target: - thread.communityFeed?.feed === - contextualCommunityFeedTarget.feed - ? 'public' - : contextualCommunityFeedTarget, + target: isLeaving ? 'public' : contextualCommunityFeedTarget, }) }} style={[a.flex_row, a.align_center, a.gap_xs]}> diff --git a/src/view/com/composer/__tests__/PostTargetControls.test.tsx b/src/view/com/composer/__tests__/PostTargetControls.test.tsx index 8ca7c1a1d..ba3637861 100644 --- a/src/view/com/composer/__tests__/PostTargetControls.test.tsx +++ b/src/view/com/composer/__tests__/PostTargetControls.test.tsx @@ -69,6 +69,19 @@ jest.mock('#/components/forms/Toggle', () => { } }) +const mockToast = jest.fn() +jest.mock('#/components/Toast', () => ({ + show: (...args: unknown[]) => mockToast(...args), +})) +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(), +})) + import {PostTargetControls} from '../PostTargetControls' const PRIVATE_TARGET: CommunityFeedTarget = { @@ -85,6 +98,41 @@ const PRIVATE_TARGET: CommunityFeedTarget = { }, } +const COMMUNITY_RECORD_TARGET: CommunityFeedTarget = { + ...PRIVATE_TARGET, + feed: 'at://did:plc:test/app.bsky.feed.generator/members', + name: 'Members Test', + config: {...PRIVATE_TARGET.config, space: undefined}, +} + +const PUBLIC_RECORD_TARGET: CommunityFeedTarget = { + ...PRIVATE_TARGET, + feed: 'at://did:plc:test/app.bsky.feed.generator/public', + name: 'Public Test', + config: { + ...PRIVATE_TARGET.config, + contentType: 'publicRecord', + visibility: 'public', + space: undefined, + }, +} + +const POLL_REMOVED_MESSAGE = + 'Polls are only available on public posts, so the poll was removed.' + +function draftPost(embed: Partial = {}) { + return {embed} as ThreadDraft['posts'][number] +} + +const TEXT_POST = draftPost() +const POLL_POST = draftPost({poll: {statements: ['a']}}) +const COMMUNITY_QUOTE_POST = draftPost({ + quote: { + type: 'link', + uri: 'https://bsky.app/profile/did:plc:author/post/3kabc?collection=community.blacksky.feed.post', + }, +}) + function thread(overrides: Partial = {}): ThreadDraft { return { posts: [], @@ -126,6 +174,8 @@ function renderControls({ } describe('PostTargetControls', () => { + beforeEach(() => mockToast.mockClear()) + it('keeps ordinary public composition on the legacy Blacksky-only toggle', () => { const {getByTestId, queryByTestId} = renderControls() @@ -176,6 +226,160 @@ describe('PostTargetControls', () => { }) }) + it('announces the poll removal when switching to a private feed', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [TEXT_POST, POLL_POST]}), + target: PRIVATE_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).toHaveBeenCalledTimes(1) + expect(mockToast).toHaveBeenCalledWith(POLL_REMOVED_MESSAGE, {type: 'info'}) + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('stays quiet when leaving the private feed', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [POLL_POST], communityFeed: PRIVATE_TARGET}), + target: PRIVATE_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: 'public', + }) + }) + + it('stays quiet when no post has a poll', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [TEXT_POST]}), + target: PRIVATE_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('announces the poll removal when switching to a community-record feed', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [POLL_POST]}), + target: COMMUNITY_RECORD_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).toHaveBeenCalledTimes(1) + expect(mockToast).toHaveBeenCalledWith(POLL_REMOVED_MESSAGE, {type: 'info'}) + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: COMMUNITY_RECORD_TARGET, + }) + }) + + it('stays quiet when the selected feed takes public posts', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [POLL_POST]}), + target: PUBLIC_RECORD_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PUBLIC_RECORD_TARGET, + }) + }) + + it('judges the selected feed, not what the thread quotes', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [POLL_POST, COMMUNITY_QUOTE_POST]}), + target: PUBLIC_RECORD_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PUBLIC_RECORD_TARGET, + }) + }) + + it('judges the selected feed, not the audience it replaces', () => { + const {dispatch, getByTestId} = renderControls({ + draft: thread({posts: [POLL_POST], blackskyOnly: true}), + target: PUBLIC_RECORD_TARGET, + }) + + fireEvent.press(getByTestId('permissioned_space')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PUBLIC_RECORD_TARGET, + }) + }) + + it('announces the poll removal when Blacksky Only is turned on', () => { + const {dispatch, getByTestId, setBlackskyOnlyDefault} = renderControls({ + draft: thread({posts: [TEXT_POST, POLL_POST]}), + }) + + fireEvent.press(getByTestId('blacksky_only')) + + expect(mockToast).toHaveBeenCalledTimes(1) + expect(mockToast).toHaveBeenCalledWith(POLL_REMOVED_MESSAGE, {type: 'info'}) + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({type: 'toggle_blacksky_only'}) + expect(setBlackskyOnlyDefault).toHaveBeenCalledWith(true) + }) + + it('stays quiet when Blacksky Only is turned on without a poll', () => { + const {dispatch, getByTestId, setBlackskyOnlyDefault} = renderControls({ + draft: thread({posts: [TEXT_POST]}), + }) + + fireEvent.press(getByTestId('blacksky_only')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({type: 'toggle_blacksky_only'}) + expect(setBlackskyOnlyDefault).toHaveBeenCalledWith(true) + }) + + it('stays quiet when Blacksky Only is turned off', () => { + const {dispatch, getByTestId, setBlackskyOnlyDefault} = renderControls({ + draft: thread({posts: [POLL_POST], blackskyOnly: true}), + }) + + fireEvent.press(getByTestId('blacksky_only')) + + expect(mockToast).not.toHaveBeenCalled() + expect(dispatch).toHaveBeenCalledTimes(1) + expect(dispatch).toHaveBeenCalledWith({type: 'toggle_blacksky_only'}) + expect(setBlackskyOnlyDefault).toHaveBeenCalledWith(false) + }) + it('does not expose private-space controls outside selected-feed context', () => { const {queryByTestId} = renderControls({ draft: thread({communityFeed: PRIVATE_TARGET}), diff --git a/src/view/com/composer/drafts/DraftItem.tsx b/src/view/com/composer/drafts/DraftItem.tsx index cc2792224..1f414894d 100644 --- a/src/view/com/composer/drafts/DraftItem.tsx +++ b/src/view/com/composer/drafts/DraftItem.tsx @@ -12,6 +12,7 @@ import {Button} from '#/components/Button' 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' +import {Poll_Stroke2_Corner0_Rounded as PollIcon} from '#/components/icons/Poll' import {CloseQuote_Stroke2_Corner0_Rounded as CloseQuoteIcon} from '#/components/icons/Quote' import {Warning_Stroke2_Corner0_Rounded as WarningIcon} from '#/components/icons/Warning' import * as MediaPreview from '#/components/MediaPreview' @@ -107,6 +108,8 @@ export function DraftItem({ {!mediaExistsOnOtherDevice && } + {post.poll && } + {hasMetadata && ( {mediaExistsOnOtherDevice && ( @@ -277,6 +280,43 @@ type LoadedImage = { alt: string } +function DraftPollPreview({poll}: {poll: {statements: string[]}}) { + const t = useTheme() + const {_} = useLingui() + const statements = poll.statements.filter(s => s.trim().length > 0) + return ( + + + + + {_( + msg({ + message: 'Poll', + comment: 'Label on a draft preview showing the draft has a poll', + }), + )} + + + {statements.map((statement, index) => ( + + {statement} + + ))} + + ) +} + function DraftMediaPreview({post}: {post: DraftPostDisplay}) { const [loadedImages, setLoadedImages] = useState([]) const [videoThumbnail, setVideoThumbnail] = useState() diff --git a/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts b/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts new file mode 100644 index 000000000..09afaa0f2 --- /dev/null +++ b/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts @@ -0,0 +1,350 @@ +import {type AppBskyDraftDefs, RichText} from '@atproto/api' + +import {type AssemblyRef} from '#/lib/api/poll' +import { + type ComposerState, + type PostDraft, +} from '#/view/com/composer/state/composer' +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 POLL_KEY = 'communityBlackskyPoll' + +const pendingRef: AssemblyRef = { + rkey: '3kassembly', + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: '["question",["first","second"]]', +} + +const createdRef: AssemblyRef = { + ...pendingRef, + conversationId: '7abcde', + reportId: 'r7abcde', +} + +function savedPoll(draft: AppBskyDraftDefs.Draft, index = 0): unknown { + return (draft.posts[index] as unknown as Record)[POLL_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 polls', () => { + it('serialises the poll as an extra property on the draft post', async () => { + const {draft} = await composerStateToDraft( + state([post({poll: {statements: ['one', '']}}, 'question')]), + ) + expect(savedPoll(draft)).toStrictEqual({statements: ['one', '']}) + }) + + it('serialises the assembly reference with the statements', async () => { + const {draft} = await composerStateToDraft( + state([ + post( + {poll: {statements: ['first', 'second'], assembly: createdRef}}, + 'question', + ), + ]), + ) + expect(savedPoll(draft)).toStrictEqual({ + statements: ['first', 'second'], + assembly: { + rkey: '3kassembly', + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: '["question",["first","second"]]', + conversationId: '7abcde', + reportId: 'r7abcde', + }, + }) + }) + + it('serialises the poll of the post that has one', async () => { + const {draft} = await composerStateToDraft( + state([ + post({}, 'lead'), + post({poll: {statements: ['first'], assembly: pendingRef}}, 'question'), + ]), + ) + expect(POLL_KEY in draft.posts[0]).toBe(false) + expect(savedPoll(draft, 1)).toStrictEqual({ + statements: ['first'], + assembly: pendingRef, + }) + }) + + it('omits the property when there is no poll', async () => { + const {draft} = await composerStateToDraft(state([post({}, 'text only')])) + expect(POLL_KEY in draft.posts[0]).toBe(false) + }) + + it('restores a poll, including unfinished and oversized statements', async () => { + const oversized = 'a' + '\u0301'.repeat(2000) + const {posts} = await draftToComposerPosts( + draftOf([draftPost({[POLL_KEY]: {statements: ['', oversized]}})]), + new Map(), + ) + expect(posts[0].embed.poll).toEqual({statements: ['', oversized]}) + }) + + it('round-trips a poll through save and restore', async () => { + const {draft} = await composerStateToDraft( + state([post({poll: {statements: ['first', 'second']}}, 'question')]), + ) + const {posts} = await draftToComposerPosts(asStored(draft), new Map()) + expect(posts[0].embed.poll).toEqual({statements: ['first', 'second']}) + expect(posts[0].embed.poll?.assembly).toBeUndefined() + expect(posts[0].richtext.text).toBe('question') + }) + + it.each([ + {kind: 'an assembly that was created', assembly: createdRef}, + {kind: 'an assembly that is still being created', assembly: pendingRef}, + ])('round-trips the reference to $kind', async ({assembly}) => { + const {draft} = await composerStateToDraft( + state([ + post({poll: {statements: ['first', 'second'], assembly}}, 'question'), + ]), + ) + const {posts} = await draftToComposerPosts(asStored(draft), new Map()) + + expect(posts[0].embed.poll).toEqual({ + statements: ['first', 'second'], + assembly, + }) + expect(posts[0].embed.poll?.assembly?.conversationId).toBe( + assembly.conversationId, + ) + expect(posts[0].embed.poll?.assembly?.reportId).toBe(assembly.reportId) + }) + + it('round-trips a saved reference through a second save', async () => { + const first = await composerStateToDraft( + state([ + post( + {poll: {statements: ['first', 'second'], assembly: pendingRef}}, + 'question', + ), + ]), + ) + const restored = await draftToComposerPosts( + asStored(first.draft), + new Map(), + ) + const second = await composerStateToDraft(state(restored.posts)) + + expect(asStored(second.draft).posts[0]).toHaveProperty(POLL_KEY, { + statements: ['first', 'second'], + assembly: pendingRef, + }) + }) + + it('restores the statements when the reference is malformed', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({ + [POLL_KEY]: { + statements: ['a'], + assembly: {rkey: '3kassembly', createdAt: 42}, + }, + }), + draftPost({[POLL_KEY]: {statements: ['b'], assembly: 'nope'}}), + ]), + new Map(), + ) + expect(posts.map(p => p.embed.poll)).toEqual([ + {statements: ['a']}, + {statements: ['b']}, + ]) + expect(posts[0].embed.poll?.assembly).toBeUndefined() + expect(posts[1].embed.poll?.assembly).toBeUndefined() + }) + + it('ignores a malformed poll property', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({[POLL_KEY]: {statements: null}}), + draftPost({[POLL_KEY]: {statements: [42]}}), + draftPost({[POLL_KEY]: 'nope'}), + ]), + new Map(), + ) + expect(posts.map(p => p.embed.poll)).toEqual([ + undefined, + undefined, + undefined, + ]) + }) + + it('drops the poll when the restored post also has a gif', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({ + [POLL_KEY]: {statements: ['a'], assembly: createdRef}, + embedExternals: [ + {uri: 'https://media.tenor.com/abc/clip.gif?hh=100&ww=200&alt=hi'}, + ], + }), + ]), + new Map(), + ) + expect(posts[0].embed.media?.type).toBe('gif') + expect(posts[0].embed.poll).toBeUndefined() + }) + + it('drops the poll when the restored post also has a quote', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({ + [POLL_KEY]: {statements: ['a']}, + embedRecords: [ + { + record: { + uri: 'at://did:plc:abc/app.bsky.feed.post/3kabc', + cid: 'bafyreicid', + }, + }, + ], + }), + ]), + new Map(), + ) + expect(posts[0].embed.quote).toBeDefined() + expect(posts[0].embed.poll).toBeUndefined() + }) + + it('drops the poll when the restored post also has a link', async () => { + const {posts} = await draftToComposerPosts( + draftOf([ + draftPost({ + [POLL_KEY]: {statements: ['a']}, + embedExternals: [{uri: 'https://example.com/article'}], + }), + ]), + new Map(), + ) + expect(posts[0].embed.link).toBeDefined() + expect(posts[0].embed.poll).toBeUndefined() + }) + + it('drops the poll when a video is pending restoration', async () => { + const path = 'video:video/mp4:abc.mp4' + const {posts, restoredVideos} = await draftToComposerPosts( + draftOf([ + draftPost({ + [POLL_KEY]: {statements: ['a']}, + embedVideos: [{localRef: {path}}], + }), + ]), + new Map([[path, 'file://abc.mp4']]), + ) + expect(restoredVideos.has(0)).toBe(true) + expect(posts[0].embed.media).toBeUndefined() + expect(posts[0].embed.poll).toBeUndefined() + }) + + it('saves a poll draft whatever its size', async () => { + const text = '\u4e2d'.repeat(1000) + const statements = [...Array(10).keys()].map(index => + String(index).repeat(400), + ) + const {draft} = await composerStateToDraft( + state([ + post({poll: {statements, assembly: createdRef}}, 'question'), + ...Array.from({length: 31}, () => post({}, text)), + ]), + ) + + expect(draft.posts).toHaveLength(32) + expect(Buffer.byteLength(JSON.stringify(draft))).toBeGreaterThan(90_000) + expect(savedPoll(draft)).toStrictEqual({statements, assembly: createdRef}) + }) + + it('includes the poll in the draft list summary', () => { + const summary = draftViewToSummary({ + view: { + id: 'draft-1', + createdAt: '2026-09-27T00:00:00.000Z', + updatedAt: '2026-09-27T00:00:00.000Z', + draft: draftOf([ + draftPost({ + [POLL_KEY]: {statements: ['shown', ''], assembly: createdRef}, + }), + draftPost({}), + ]), + }, + analytics: {logger: {warn: jest.fn()}} as never, + }) + expect(summary.posts[0].poll).toEqual({ + statements: ['shown', ''], + assembly: createdRef, + }) + expect(summary.posts[1].poll).toBeUndefined() + }) +}) diff --git a/src/view/com/composer/drafts/state/api.ts b/src/view/com/composer/drafts/state/api.ts index d09d51e93..db7de62ee 100644 --- a/src/view/com/composer/drafts/state/api.ts +++ b/src/view/com/composer/drafts/state/api.ts @@ -4,6 +4,7 @@ import {AppBskyDraftDefs, AtUri, RichText} from '@atproto/api' import {nanoid} from 'nanoid/non-secure' +import {decodePollDraft} from '#/lib/api/poll' import {resolveLink} from '#/lib/api/resolve' import {getDeviceName} from '#/lib/deviceName' import {getImageDim} from '#/lib/media/manip' @@ -27,6 +28,18 @@ import {logger} from './logger' import {type DraftPostDisplay, type DraftSummary} from './schema' import * as storage from './storage' +const DRAFT_POLL_KEY = 'communityBlackskyPoll' + +// 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 +} + +function readDraftPoll(post: DraftPostWithPoll) { + return decodePollDraft(post[DRAFT_POLL_KEY]) +} + const TENOR_HOSTNAME = 'media.tenor.com' const KLIPY_HOSTNAME = 'static.klipy.com' @@ -136,6 +149,13 @@ async function postDraftToServerPost( } } + if (post.embed.poll) { + const {statements, assembly} = post.embed.poll + ;(draftPost as DraftPostWithPoll)[DRAFT_POLL_KEY] = assembly + ? {statements, assembly} + : {statements} + } + // Add quote record embed if (post.embed.quote) { const resolved = await resolveLink( @@ -433,6 +453,7 @@ export function draftViewToSummary({ images: images.length > 0 ? images : undefined, video: videos[0], // Only one video per post gif, + poll: readDraftPoll(post), } }) @@ -624,6 +645,19 @@ export async function draftToComposerPosts( } } + // Restoration installs embeds directly, bypassing the reducer's + // exclusivity guards, and a video is only attached after this returns. + const poll = readDraftPoll(post) + if ( + poll && + !embed.media && + !embed.link && + !embed.quote && + !restoredVideos.has(index) + ) { + embed.poll = poll + } + // Parse labels const labels: string[] = [] if (post.labels && 'values' in post.labels) { diff --git a/src/view/com/composer/drafts/state/schema.ts b/src/view/com/composer/drafts/state/schema.ts index 9f88aa07d..d80339249 100644 --- a/src/view/com/composer/drafts/state/schema.ts +++ b/src/view/com/composer/drafts/state/schema.ts @@ -4,6 +4,8 @@ */ import {type AppBskyDraftDefs} from '@atproto/api' +import {type PollDraft} from '#/lib/api/poll' + /** * Reference to locally cached media file for display */ @@ -43,6 +45,7 @@ export type DraftPostDisplay = { video?: LocalMediaDisplay /** GIF data (from URL) */ gif?: GifDisplay + poll?: PollDraft } /** diff --git a/src/view/com/composer/poll/PollEditor.tsx b/src/view/com/composer/poll/PollEditor.tsx new file mode 100644 index 000000000..5352012db --- /dev/null +++ b/src/view/com/composer/poll/PollEditor.tsx @@ -0,0 +1,235 @@ +import {useState} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' +import {nanoid} from 'nanoid/non-secure' +import {countGraphemes} from 'unicode-segmenter/grapheme' + +import { + getStatementIssues, + isPollTopicPublishable, + POLL_MAX_STATEMENTS, + POLL_STATEMENT_MAX_CHARS, + POLL_STATEMENT_MAX_GRAPHEMES, + type PollDraft, +} from '#/lib/api/poll' +import {type PostAction} from '#/view/com/composer/state/composer' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import * as TextField from '#/components/forms/TextField' +import {PlusLarge_Stroke2_Corner0_Rounded as PlusIcon} from '#/components/icons/Plus' +import {Poll_Stroke2_Corner0_Rounded as PollIcon} from '#/components/icons/Poll' +import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times' +import {VoteButtons} from '#/components/Post/Embed/ExternalEmbed/VoteButtons' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' + +export function PollEditor({ + poll, + text, + dispatch, +}: { + poll: PollDraft + text: string + dispatch: (action: PostAction) => void +}) { + const t = useTheme() + const {t: l} = useLingui() + const ax = useAnalytics() + const canAdd = poll.statements.length < POLL_MAX_STATEMENTS + const canRemoveStatement = poll.statements.length > 1 + const issues = getStatementIssues(poll.statements) + const isTopicMissing = text.trim().length === 0 + const isTopicInvalid = !isTopicMissing && !isPollTopicPublishable(text) + const [rowKeys, setRowKeys] = useState(() => + poll.statements.map(() => nanoid()), + ) + + return ( + + + + + + + Poll + + + + + + + {(isTopicMissing || isTopicInvalid) && ( + + {isTopicInvalid ? ( + + Your post text contains characters that cannot be saved. + + ) : ( + Add post text to ask your question. + )} + + )} + + {poll.statements.map((statement, index) => { + const issue = issues[index] + const graphemes = countGraphemes(statement.trim()) + const isInvalid = + issue === 'too_long' || issue === 'invalid' || issue === 'duplicate' + const isBlankExtra = issue === 'empty' && canRemoveStatement + const isOverByteCap = + issue === 'too_long' && graphemes <= POLL_STATEMENT_MAX_GRAPHEMES + return ( + + + + + + dispatch({ + type: 'embed_update_poll_statement', + index, + text: next, + }) + } + multiline + /> + + + {canRemoveStatement && ( + + )} + + + {issue === 'invalid' ? ( + + This statement contains characters that cannot be saved. + + ) : isOverByteCap ? ( + This statement is too long. Shorten it to post. + ) : issue === 'duplicate' ? ( + This statement repeats another one. + ) : isBlankExtra ? ( + Add text or remove this statement to post. + ) : ( + `${graphemes} / ${POLL_STATEMENT_MAX_GRAPHEMES}` + )} + + + ) + })} + + {canAdd && ( + + )} + + + {}} /> + + + + Your post text is the question. + + + Statements and votes are public on People's Assembly. + + + + ) +} diff --git a/src/view/com/composer/poll/SelectPollBtn.tsx b/src/view/com/composer/poll/SelectPollBtn.tsx new file mode 100644 index 000000000..15e8fb840 --- /dev/null +++ b/src/view/com/composer/poll/SelectPollBtn.tsx @@ -0,0 +1,73 @@ +import {useCallback} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' + +import {Nux, useNux, useSaveNux} from '#/state/queries/nuxs' +import {atoms as a, useTheme} from '#/alf' +import {Button} from '#/components/Button' +import {Poll_Stroke2_Corner0_Rounded as PollIcon} from '#/components/icons/Poll' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' + +type Props = { + onPress: () => void + disabled?: boolean +} + +export function SelectPollBtn({onPress, disabled}: Props) { + const ax = useAnalytics() + const {t: l} = useLingui() + const t = useTheme() + const nux = useNux(Nux.ComposerPoll) + const {mutate: saveNux} = useSaveNux() + const isNew = nux.status === 'ready' && !nux.nux?.completed + + const onPressAddPoll = useCallback(() => { + ax.metric('composer:poll:open', {}) + if (isNew) { + saveNux({id: Nux.ComposerPoll, data: undefined, completed: true}) + } + onPress() + }, [ax, isNew, saveNux, onPress]) + + return ( + + + {isNew && !disabled && ( + + + + New + + + + )} + + ) +} diff --git a/src/view/com/composer/poll/__tests__/PollEditor.test.tsx b/src/view/com/composer/poll/__tests__/PollEditor.test.tsx new file mode 100644 index 000000000..9dbc84a6c --- /dev/null +++ b/src/view/com/composer/poll/__tests__/PollEditor.test.tsx @@ -0,0 +1,570 @@ +import {type useEffect, useReducer, type useRef} from 'react' +import {act, fireEvent, render} from '@testing-library/react-native' + +import { + composerReducer, + type ComposerState, + createComposerState, + type PostAction, +} from '#/view/com/composer/state/composer' + +type ReactHooks = {useEffect: typeof useEffect; useRef: typeof useRef} + +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}), + 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('#/components/Typography', () => { + const {Text} = require('react-native') + return {Text} +}) +jest.mock('#/components/icons/Poll', () => ({ + Poll_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/Plus', () => ({ + PlusLarge_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/icons/Times', () => ({ + TimesLarge_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/Button', () => { + const {Pressable, Text} = require('react-native') + return { + Button: ({ + children, + label, + onPress, + testID, + }: { + children: React.ReactNode + label: string + onPress: () => void + testID?: string + }) => ( + + {children} + + ), + ButtonText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + ButtonIcon: () => null, + } +}) + +const mockInputLifecycle = jest.fn() +jest.mock('#/components/forms/TextField', () => { + const hooks = jest.requireActual('react') + const {TextInput} = require('react-native') + return { + Root: ({children}: {children: React.ReactNode}) => children, + Input: ({ + label, + maxLength, + onChangeText, + placeholder, + testID, + value, + }: { + label: string + maxLength: number + onChangeText: (text: string) => void + placeholder: string + testID: string + value: string + }) => { + const mountedWith = hooks.useRef(value) + hooks.useEffect(() => { + const initial = mountedWith.current + mockInputLifecycle('mount', initial) + return () => mockInputLifecycle('unmount', initial) + }, []) + return ( + + ) + }, + } +}) + +const mockVoteButtons = jest.fn() +jest.mock('#/components/Post/Embed/ExternalEmbed/VoteButtons', () => { + const {Pressable} = require('react-native') + return { + VoteButtons: (props: {disabled?: boolean}) => { + mockVoteButtons(props.disabled) + return ( + + ) + }, + } +}) + +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(), +})) + +import {PollEditor} from '../PollEditor' + +const INVALID_HINT = 'This statement contains characters that cannot be saved.' +const TOO_LONG_HINT = 'This statement is too long. Shorten it to post.' +const BLANK_HINT = 'Add text or remove this statement to post.' +const DUPLICATE_HINT = 'This statement repeats another one.' +const TOPIC_MISSING_HINT = 'Add post text to ask your question.' +const TOPIC_INVALID_HINT = + 'Your post text contains characters that cannot be saved.' +const QUESTION_LINE = 'Your post text is the question.' +const PUBLIC_LINE = "Statements and votes are public on People's Assembly." + +function composerWith(statements: string[]): ComposerState { + let state = createComposerState({ + initText: undefined, + initMention: undefined, + initImageUris: undefined, + initQuoteUri: undefined, + initInteractionSettings: undefined, + }) + const postId = state.thread.posts[0].id + const actions: PostAction[] = [ + {type: 'embed_add_poll'}, + ...statements.slice(1).map(() => ({ + type: 'embed_add_poll_statement' as const, + })), + ...statements.map((text, index) => ({ + type: 'embed_update_poll_statement' as const, + index, + text, + })), + ] + for (const postAction of actions) { + state = composerReducer(state, {type: 'update_post', postId, postAction}) + } + return state +} + +const mockDispatch = jest.fn() + +function ComposerHarness({ + statements, + text, +}: { + statements: string[] + text: string +}) { + const [state, dispatch] = useReducer( + composerReducer, + statements, + composerWith, + ) + const post = state.thread.posts[0] + if (!post.embed.poll) return null + return ( + { + mockDispatch(postAction) + dispatch({type: 'update_post', postId: post.id, postAction}) + }} + /> + ) +} + +function renderEditor(statements: string[], text = 'What should we do?') { + return render() +} + +function lifecycle(kind: 'mount' | 'unmount') { + return (mockInputLifecycle.mock.calls as [string, string][]) + .filter(([event]) => event === kind) + .map(([, value]) => value) +} + +describe('PollEditor', () => { + let consoleError: jest.SpyInstance + + beforeEach(() => { + jest.clearAllMocks() + consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + consoleError.mockRestore() + }) + + it('reports an edit with the index of the statement', () => { + const {getByTestId} = renderEditor(['one', 'two']) + + expect(getByTestId('pollStatementInput-1')).toHaveProp( + 'accessibilityLabel', + 'Statement 2', + ) + fireEvent.changeText(getByTestId('pollStatementInput-1'), 'changed') + + expect(mockDispatch).toHaveBeenCalledTimes(1) + expect(mockDispatch).toHaveBeenCalledWith({ + type: 'embed_update_poll_statement', + index: 1, + text: 'changed', + }) + expect(getByTestId('pollStatementInput-0')).toHaveProp('value', 'one') + expect(getByTestId('pollStatementInput-1')).toHaveProp('value', 'changed') + }) + + it('stops every statement field at the longest text that can be stored', () => { + const {getByTestId} = renderEditor(['one', 'two']) + + expect(getByTestId('pollStatementInput-0')).toHaveProp('maxLength', 997) + expect(getByTestId('pollStatementInput-1')).toHaveProp('maxLength', 997) + }) + + it('adds a statement and reports the new count', () => { + const {getByTestId} = renderEditor(['one', 'two', 'three']) + + fireEvent.press(getByTestId('addPollStatementBtn')) + + expect(mockMetric).toHaveBeenCalledTimes(1) + expect(mockMetric).toHaveBeenCalledWith('composer:poll:statementAdd', { + count: 4, + }) + expect(mockDispatch).toHaveBeenCalledTimes(1) + expect(mockDispatch).toHaveBeenCalledWith({ + type: 'embed_add_poll_statement', + }) + }) + + it('hides the add row at ten statements', () => { + const nine = renderEditor(Array.from({length: 9}, (_, i) => `s${i}`)) + expect(nine.getByTestId('addPollStatementBtn')).toBeTruthy() + nine.unmount() + + const ten = renderEditor(Array.from({length: 10}, (_, i) => `s${i}`)) + expect(ten.getByTestId('pollStatementInput-9')).toBeTruthy() + expect(ten.queryByTestId('addPollStatementBtn')).toBeNull() + }) + + it('hides the per-statement remove when there is one statement', () => { + const {queryByTestId} = renderEditor(['only']) + expect(queryByTestId('pollStatementRemove-0')).toBeNull() + }) + + it('removes a statement by its index', () => { + const {getByTestId} = renderEditor(['one', 'two', 'three']) + + fireEvent.press(getByTestId('pollStatementRemove-1')) + + expect(mockDispatch).toHaveBeenCalledTimes(1) + expect(mockDispatch).toHaveBeenCalledWith({ + type: 'embed_remove_poll_statement', + index: 1, + }) + expect(mockMetric).not.toHaveBeenCalled() + }) + + it('removes the poll and reports it', () => { + const {getByTestId, queryByTestId} = renderEditor(['one']) + + fireEvent.press(getByTestId('removePollBtn')) + + expect(mockMetric).toHaveBeenCalledTimes(1) + expect(mockMetric).toHaveBeenCalledWith('composer:poll:remove', {}) + expect(mockDispatch).toHaveBeenCalledTimes(1) + expect(mockDispatch).toHaveBeenCalledWith({type: 'embed_remove_poll'}) + expect(queryByTestId('pollEditor')).toBeNull() + }) + + it('shows the grapheme counter for a publishable statement', () => { + const {getByTestId} = renderEditor([' fine ']) + const hint = getByTestId('pollStatementHint-0') + expect(hint).toHaveTextContent('4 / 400', {exact: true}) + expect(hint).not.toHaveStyle({color: 'negative_500'}) + }) + + it('explains a blank statement only when it can be removed', () => { + const extra = renderEditor(['one', ' ']) + expect(extra.getByTestId('pollStatementHint-0')).toHaveTextContent( + '3 / 400', + {exact: true}, + ) + const blank = extra.getByTestId('pollStatementHint-1') + expect(blank).toHaveTextContent(BLANK_HINT, {exact: true}) + expect(blank).not.toHaveStyle({color: 'negative_500'}) + extra.unmount() + + const only = renderEditor(['']) + expect(only.getByTestId('pollStatementHint-0')).toHaveTextContent( + '0 / 400', + {exact: true}, + ) + }) + + it('explains a statement over the byte cap but under the grapheme cap', () => { + const cluster = 'a' + '\u20dd'.repeat(3) + const atCap = renderEditor([cluster.repeat(200)]) + expect(atCap.getByTestId('pollStatementHint-0')).toHaveTextContent( + '200 / 400', + {exact: true}, + ) + atCap.unmount() + + const overCap = renderEditor([cluster.repeat(201)]) + const hint = overCap.getByTestId('pollStatementHint-0') + expect(hint).toHaveTextContent(TOO_LONG_HINT, {exact: true}) + expect(hint).toHaveStyle({color: 'negative_500'}) + }) + + it('keeps the counter for a statement over the grapheme cap', () => { + const {getByTestId} = renderEditor(['a'.repeat(401)]) + const hint = getByTestId('pollStatementHint-0') + expect(hint).toHaveTextContent('401 / 400', {exact: true}) + expect(hint).toHaveStyle({color: 'negative_500'}) + }) + + it('explains a statement with characters that cannot be saved', () => { + const {getByTestId} = renderEditor(['a\u0000b', 'a\ud800']) + for (const index of [0, 1]) { + const hint = getByTestId(`pollStatementHint-${index}`) + expect(hint).toHaveTextContent(INVALID_HINT, {exact: true}) + expect(hint).toHaveStyle({color: 'negative_500'}) + } + }) + + it('explains a statement that repeats an earlier one', () => { + const {getByTestId} = renderEditor([ + 'Fund the library', + 'Close the pool', + ' fund the LIBRARY ', + ]) + + expect(getByTestId('pollStatementHint-0')).toHaveTextContent('16 / 400', { + exact: true, + }) + expect(getByTestId('pollStatementHint-0')).not.toHaveStyle({ + color: 'negative_500', + }) + expect(getByTestId('pollStatementHint-1')).toHaveTextContent('14 / 400', { + exact: true, + }) + const repeat = getByTestId('pollStatementHint-2') + expect(repeat).toHaveTextContent(DUPLICATE_HINT, {exact: true}) + expect(repeat).toHaveStyle({color: 'negative_500'}) + }) + + it('drops the repeat hint once the statement differs', () => { + const {getByTestId} = renderEditor(['same', 'same']) + expect(getByTestId('pollStatementHint-1')).toHaveTextContent( + DUPLICATE_HINT, + {exact: true}, + ) + + fireEvent.changeText(getByTestId('pollStatementInput-1'), 'different') + + const hint = getByTestId('pollStatementHint-1') + expect(hint).toHaveTextContent('9 / 400', {exact: true}) + expect(hint).not.toHaveStyle({color: 'negative_500'}) + }) + + it('does not count blank statements as repeats of each other', () => { + const {getByTestId} = renderEditor(['', '']) + for (const index of [0, 1]) { + expect(getByTestId(`pollStatementHint-${index}`)).toHaveTextContent( + BLANK_HINT, + {exact: true}, + ) + } + }) + + it.each([ + {kind: 'empty', text: ''}, + {kind: 'only whitespace', text: ' \n\t '}, + ])('asks for post text when it is $kind', ({text}) => { + const {getByTestId} = renderEditor(['one'], text) + const hint = getByTestId('pollTopicHint') + expect(hint).toHaveTextContent(TOPIC_MISSING_HINT, {exact: true}) + expect(hint).not.toHaveStyle({color: 'negative_500'}) + }) + + it.each([ + {kind: 'a null character', text: 'a\u0000b'}, + {kind: 'a lone surrogate', text: 'a\ud800'}, + ])('explains post text with $kind', ({text}) => { + const {getByTestId} = renderEditor(['one'], text) + const hint = getByTestId('pollTopicHint') + expect(hint).toHaveTextContent(TOPIC_INVALID_HINT, {exact: true}) + expect(hint).toHaveStyle({color: 'negative_500'}) + }) + + it('shows no post text hint when there is post text', () => { + const {queryByTestId, queryByText} = renderEditor(['one'], 'A question') + expect(queryByTestId('pollTopicHint')).toBeNull() + expect(queryByText(TOPIC_MISSING_HINT)).toBeNull() + expect(queryByText(TOPIC_INVALID_HINT)).toBeNull() + }) + + it('follows the post text as it changes', () => { + const {queryByTestId, rerender} = renderEditor(['one'], '') + expect(queryByTestId('pollTopicHint')).toHaveTextContent( + TOPIC_MISSING_HINT, + {exact: true}, + ) + + rerender() + + expect(queryByTestId('pollTopicHint')).toBeNull() + }) + + it('says where the question comes from and that the poll is public', () => { + const {getByText, queryByText} = renderEditor(['one']) + + expect(getByText(QUESTION_LINE, {exact: true})).toBeTruthy() + expect(getByText(PUBLIC_LINE, {exact: true})).toBeTruthy() + expect(getByText(QUESTION_LINE)).not.toBe(getByText(PUBLIC_LINE)) + expect(queryByText(/other apps show your post text only/)).toBeNull() + expect(queryByText(/Readers vote Agree/)).toBeNull() + }) + + it('hides the disabled vote preview from assistive technology', () => { + const {getByTestId, queryByTestId} = renderEditor(['one']) + + expect(mockVoteButtons).toHaveBeenCalledWith(true) + expect(queryByTestId('pollVote-agree')).toBeNull() + expect( + getByTestId('pollVote-agree', {includeHiddenElements: true}), + ).toBeTruthy() + + const preview = getByTestId('pollVotePreview', { + includeHiddenElements: true, + }) + expect(preview).toHaveProp('aria-hidden', true) + expect(preview).toHaveProp('accessibilityElementsHidden', true) + expect(preview).toHaveProp( + 'importantForAccessibility', + 'no-hide-descendants', + ) + expect(preview).toHaveProp('pointerEvents', 'none') + }) + + it('unmounts only the removed row so the others keep their input', () => { + const {getByTestId, queryByTestId} = renderEditor(['A', 'B', 'C']) + expect(lifecycle('mount')).toEqual(['A', 'B', 'C']) + + fireEvent.press(getByTestId('pollStatementRemove-0')) + + expect(lifecycle('unmount')).toEqual(['A']) + expect(lifecycle('mount')).toEqual(['A', 'B', 'C']) + expect(getByTestId('pollStatementInput-0')).toHaveProp('value', 'B') + expect(getByTestId('pollStatementInput-1')).toHaveProp('value', 'C') + expect(queryByTestId('pollStatementInput-2')).toBeNull() + expect(consoleError).not.toHaveBeenCalled() + }) + + it('mounts one new row when a statement is added', () => { + const {getByTestId} = renderEditor(['A', 'B']) + + fireEvent.press(getByTestId('addPollStatementBtn')) + + expect(lifecycle('mount')).toEqual(['A', 'B', '']) + expect(lifecycle('unmount')).toEqual([]) + expect(getByTestId('pollStatementInput-2')).toHaveProp('value', '') + expect(consoleError).not.toHaveBeenCalled() + }) + + it('keeps the last row mounted when a removal is pressed twice', () => { + const {getByTestId, queryByTestId} = renderEditor(['A', 'B']) + const remove = getByTestId('pollStatementRemove-0') + + act(() => { + fireEvent.press(remove) + fireEvent.press(remove) + }) + + expect(mockDispatch).toHaveBeenCalledTimes(2) + expect(lifecycle('unmount')).toEqual(['A']) + expect(lifecycle('mount')).toEqual(['A', 'B']) + expect(getByTestId('pollStatementInput-0')).toHaveProp('value', 'B') + expect(queryByTestId('pollStatementInput-1')).toBeNull() + expect(queryByTestId('pollStatementRemove-0')).toBeNull() + expect(consoleError).not.toHaveBeenCalled() + }) + + it('stops adding rows at ten when the add row is pressed twice', () => { + const {getByTestId, queryByTestId} = renderEditor( + Array.from({length: 9}, (_, i) => `s${i}`), + ) + const add = getByTestId('addPollStatementBtn') + + act(() => { + fireEvent.press(add) + fireEvent.press(add) + }) + + expect(mockDispatch).toHaveBeenCalledTimes(2) + expect(lifecycle('mount')).toHaveLength(10) + expect(lifecycle('unmount')).toEqual([]) + expect(getByTestId('pollStatementInput-9')).toHaveProp('value', '') + expect(queryByTestId('pollStatementInput-10')).toBeNull() + expect(queryByTestId('addPollStatementBtn')).toBeNull() + expect(consoleError).not.toHaveBeenCalled() + }) +}) diff --git a/src/view/com/composer/poll/__tests__/SelectPollBtn.test.tsx b/src/view/com/composer/poll/__tests__/SelectPollBtn.test.tsx new file mode 100644 index 000000000..fd5e8e698 --- /dev/null +++ b/src/view/com/composer/poll/__tests__/SelectPollBtn.test.tsx @@ -0,0 +1,205 @@ +import {fireEvent, render} from '@testing-library/react-native' + +import {Nux} from '#/state/queries/nuxs/definitions' + +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}), + 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: () => '#000'}), + }), + } +}) +jest.mock('#/components/Typography', () => { + const {Text} = require('react-native') + return {Text} +}) +jest.mock('#/components/icons/Poll', () => ({ + Poll_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/Button', () => { + const {Pressable} = require('react-native') + return { + Button: ({ + accessibilityHint, + children, + disabled, + label, + onPress, + testID, + }: { + accessibilityHint: string + children: React.ReactNode + disabled?: boolean + label: string + onPress: () => void + testID?: string + }) => ( + + {children} + + ), + } +}) + +const mockMetric = jest.fn() +jest.mock('#/analytics', () => ({ + useAnalytics: () => ({metric: mockMetric}), +})) + +type NuxState = + | { + status: 'ready' + nux: + | {id: Nux.ComposerPoll; completed: boolean; data: undefined} + | undefined + } + | {status: 'loading' | 'error'; nux: undefined} + +const UNSEEN: NuxState = {status: 'ready', nux: undefined} +const SEEN: NuxState = { + status: 'ready', + nux: {id: Nux.ComposerPoll, completed: true, data: undefined}, +} + +let mockNux: NuxState +const mockSaveNux = jest.fn() +jest.mock('#/state/queries/nuxs', () => ({ + Nux: {ComposerPoll: 'ComposerPoll'}, + useNux: () => mockNux, + useSaveNux: () => ({mutate: mockSaveNux}), +})) + +import {SelectPollBtn} from '../SelectPollBtn' + +describe('SelectPollBtn', () => { + beforeEach(() => { + jest.clearAllMocks() + mockNux = SEEN + }) + + it('opens the poll editor and reports it', () => { + const onPress = jest.fn() + const {getByTestId} = render() + + const button = getByTestId('openPollBtn') + expect(button).toHaveProp('accessibilityLabel', 'Add poll') + expect(button).toHaveProp( + 'accessibilityHint', + 'Attaches a poll to this post', + ) + fireEvent.press(button) + + expect(onPress).toHaveBeenCalledTimes(1) + expect(mockMetric).toHaveBeenCalledTimes(1) + expect(mockMetric).toHaveBeenCalledWith('composer:poll:open', {}) + expect(mockSaveNux).not.toHaveBeenCalled() + }) + + it('shows the New badge until the first press saves the NUX', () => { + mockNux = UNSEEN + const onPress = jest.fn() + const {getByTestId, getByText, queryByText, rerender} = render( + , + ) + expect(getByText('New')).toBeTruthy() + + fireEvent.press(getByTestId('openPollBtn')) + + expect(mockSaveNux).toHaveBeenCalledTimes(1) + expect(mockSaveNux).toHaveBeenCalledWith({ + id: Nux.ComposerPoll, + data: undefined, + completed: true, + }) + expect(onPress).toHaveBeenCalledTimes(1) + + mockNux = SEEN + rerender() + + expect(queryByText('New')).toBeNull() + }) + + it('shows the New badge for a saved but incomplete NUX', () => { + mockNux = { + status: 'ready', + nux: {id: Nux.ComposerPoll, completed: false, data: undefined}, + } + const {getByText} = render() + expect(getByText('New')).toBeTruthy() + }) + + it.each([{status: 'loading' as const}, {status: 'error' as const}])( + 'shows no badge and saves nothing while the NUX is $status', + ({status}) => { + mockNux = {status, nux: undefined} + const onPress = jest.fn() + const {getByTestId, queryByText} = render( + , + ) + expect(queryByText('New')).toBeNull() + + fireEvent.press(getByTestId('openPollBtn')) + + expect(onPress).toHaveBeenCalledTimes(1) + expect(mockSaveNux).not.toHaveBeenCalled() + }, + ) + + it('blocks the press and hides the badge while disabled', () => { + mockNux = UNSEEN + const onPress = jest.fn() + const {getByTestId, queryByText} = render( + , + ) + + const button = getByTestId('openPollBtn') + expect(button).toHaveProp('accessibilityState', {disabled: true}) + expect(queryByText('New')).toBeNull() + fireEvent.press(button) + + expect(onPress).not.toHaveBeenCalled() + expect(mockMetric).not.toHaveBeenCalled() + expect(mockSaveNux).not.toHaveBeenCalled() + }) + + it('is enabled by default', () => { + const {getByTestId} = render() + expect(getByTestId('openPollBtn')).toHaveProp('accessibilityState', { + disabled: false, + }) + }) +}) diff --git a/src/view/com/composer/state/__tests__/composer-poll.test.ts b/src/view/com/composer/state/__tests__/composer-poll.test.ts new file mode 100644 index 000000000..80896ec40 --- /dev/null +++ b/src/view/com/composer/state/__tests__/composer-poll.test.ts @@ -0,0 +1,937 @@ +import {RichText} from '@atproto/api' + +import {type AssemblyRef} from '#/lib/api/poll' +import {type ComposerImage} from '#/state/gallery' +import {type Gif} from '#/features/gifPicker/types' +import { + type ComposerAction, + composerReducer, + type ComposerState, + createComposerState, + isPollAllowed, + isPollPostable, + isPublicTarget, + type PostDraft, + postHasAttachment, + postHasContent, + type ThreadDraft, + threadHasPoll, +} 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 + +const spaceTarget = { + feed: 'at://did:plc:test/app.bsky.feed.generator/private', + name: 'Private', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config' as const, + contentType: 'communityRecord' as const, + visibility: 'gated' as const, + space: 'at://did:plc:test/space/community.blacksky.feed/private', + group: 'members', + createdAt: '2026-08-30T00:00:00.000Z', + }, +} + +const communityRecordTarget = { + ...spaceTarget, + feed: 'at://did:plc:test/app.bsky.feed.generator/members', + name: 'Members', + config: {...spaceTarget.config, space: undefined}, +} + +const publicRecordTarget = { + ...communityRecordTarget, + feed: 'at://did:plc:test/app.bsky.feed.generator/open', + name: 'Open', + config: { + ...communityRecordTarget.config, + contentType: 'publicRecord' as const, + visibility: 'public' as const, + }, +} + +const SPACE = 'at://did:plc:test/space/community.blacksky.feed/private' +const SPACE_POST = `${SPACE}/did:plc:author/app.bsky.feed.post/3kabc` +const COMMUNITY_POST = 'at://did:plc:author/community.blacksky.feed.post/3kabc' +const PUBLIC_POST = 'at://did:plc:author/app.bsky.feed.post/3kabc' +const COMMUNITY_POST_LINK = + 'https://bsky.app/profile/did:plc:author/post/3kabc?collection=community.blacksky.feed.post' + +const pendingRef: AssemblyRef = { + rkey: '3kassembly', + createdAt: '2026-09-27T12:00:00.000Z', + fingerprint: '["question",["first"]]', +} + +const createdRef: AssemblyRef = { + ...pendingRef, + conversationId: '7abcde', + reportId: 'r7abcde', +} + +type PostAction = Extract['postAction'] + +function initialState(): ComposerState { + return createComposerState({ + initText: undefined, + initMention: undefined, + initImageUris: undefined, + initQuoteUri: undefined, + initInteractionSettings: undefined, + }) +} + +function apply(state: ComposerState, actions: PostAction[]): ComposerState { + for (const postAction of actions) { + state = composerReducer(state, { + type: 'update_post', + postId: state.thread.posts[0].id, + postAction, + }) + } + return state +} + +function draftAfter(actions: PostAction[]) { + return apply(initialState(), actions).thread.posts[0] +} + +function updatePost( + state: ComposerState, + index: number, + postAction: PostAction, +): ComposerState { + return composerReducer(state, { + type: 'update_post', + postId: state.thread.posts[index].id, + postAction, + }) +} + +function threadOfTwo(): ComposerState { + return composerReducer(initialState(), {type: 'add_post'}) +} + +function withPosts( + state: ComposerState, + change: (post: PostDraft, index: number) => PostDraft, +): ComposerState { + return { + ...state, + thread: {...state.thread, posts: state.thread.posts.map(change)}, + } +} + +function withPollOnEveryPost(state: ComposerState): ComposerState { + return withPosts(state, (post, index) => ({ + ...post, + embed: {...post.embed, poll: {statements: [`statement ${index}`]}}, + })) +} + +function pollBesideCommunityQuote(): ComposerState { + let state = updatePost(threadOfTwo(), 0, {type: 'embed_add_poll'}) + state = updatePost(state, 0, { + type: 'embed_update_poll_statement', + index: 0, + text: 'keep', + }) + return updatePost(state, 1, {type: 'embed_add_uri', uri: COMMUNITY_POST_LINK}) +} + +function threadWith(overrides: Partial): ThreadDraft { + return {...initialState().thread, ...overrides} +} + +function threadQuoting(uri: string): ThreadDraft { + const state = withPosts(threadOfTwo(), (post, index) => + index === 1 + ? {...post, embed: {...post.embed, quote: {type: 'link', uri}}} + : post, + ) + return state.thread +} + +describe('composer polls', () => { + it('adds a poll with one empty statement', () => { + const post = draftAfter([{type: 'embed_add_poll'}]) + expect(post.embed.poll).toEqual({statements: ['']}) + }) + + it('edits, adds and removes statements', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_update_poll_statement', index: 0, text: 'first'}, + {type: 'embed_add_poll_statement'}, + {type: 'embed_update_poll_statement', index: 1, text: 'second'}, + {type: 'embed_add_poll_statement'}, + {type: 'embed_remove_poll_statement', index: 0}, + ]) + expect(post.embed.poll).toEqual({statements: ['second', '']}) + }) + + it('ignores an out-of-range statement update', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_update_poll_statement', index: 3, text: 'nope'}, + ]) + expect(post.embed.poll).toEqual({statements: ['']}) + }) + + it('caps statements at ten', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + ...Array.from({length: 12}, () => ({ + type: 'embed_add_poll_statement' as const, + })), + ]) + expect(post.embed.poll?.statements).toHaveLength(10) + }) + + it('never removes the last statement', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_remove_poll_statement', index: 0}, + ]) + expect(post.embed.poll?.statements).toHaveLength(1) + }) + + it('removes the poll', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_remove_poll'}, + ]) + expect(post.embed.poll).toBeUndefined() + }) + + it('refuses a poll when images, a gif or a link are attached', () => { + expect( + draftAfter([ + {type: 'embed_add_images', images: [image]}, + {type: 'embed_add_poll'}, + ]).embed.poll, + ).toBeUndefined() + expect( + draftAfter([ + {type: 'embed_add_gif', gif: {} as Gif}, + {type: 'embed_add_poll'}, + ]).embed.poll, + ).toBeUndefined() + expect( + draftAfter([ + {type: 'embed_add_uri', uri: 'https://example.com/article'}, + {type: 'embed_add_poll'}, + ]).embed.poll, + ).toBeUndefined() + }) + + it('refuses a poll when a quote is attached', () => { + const post = draftAfter([ + { + type: 'embed_add_uri', + uri: 'https://bsky.app/profile/alice.test/post/3kabc', + }, + {type: 'embed_add_poll'}, + ]) + expect(post.embed.quote).toBeDefined() + expect(post.embed.poll).toBeUndefined() + }) + + it('refuses media, gifs, video, links and quotes once a poll exists', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_add_images', images: [image]}, + {type: 'embed_add_gif', gif: {} as Gif}, + { + type: 'embed_add_video', + asset: {} as never, + abortController: new AbortController(), + }, + {type: 'embed_add_uri', uri: 'https://example.com/article'}, + { + type: 'embed_add_uri', + uri: 'https://bsky.app/profile/alice.test/post/3kabc', + }, + ]) + expect(post.embed.poll).toEqual({statements: ['']}) + expect(post.embed.media).toBeUndefined() + expect(post.embed.link).toBeUndefined() + expect(post.embed.quote).toBeUndefined() + }) + + it('keeps a poll on a new thread post independent of the first', () => { + let state = apply(initialState(), [{type: 'embed_add_poll'}]) + state = composerReducer(state, {type: 'add_post'}) + expect(state.thread.posts).toHaveLength(2) + expect(state.thread.posts[0].embed.poll).toEqual({statements: ['']}) + expect(state.thread.posts[1].embed.poll).toBeUndefined() + }) +}) + +describe('one poll per thread', () => { + it('refuses a second poll while another post has one', () => { + const state = updatePost(threadOfTwo(), 0, {type: 'embed_add_poll'}) + const next = updatePost(state, 1, {type: 'embed_add_poll'}) + + expect(next).toBe(state) + expect(next.thread.posts.map(post => post.embed.poll)).toEqual([ + {statements: ['']}, + undefined, + ]) + }) + + it('refuses a second poll whichever post holds the first', () => { + const state = updatePost(threadOfTwo(), 1, {type: 'embed_add_poll'}) + const next = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(next).toBe(state) + expect(next.thread.posts.map(post => post.embed.poll)).toEqual([ + undefined, + {statements: ['']}, + ]) + }) + + it('accepts a poll on another post once the first is removed', () => { + let state = updatePost(threadOfTwo(), 0, {type: 'embed_add_poll'}) + state = updatePost(state, 0, {type: 'embed_remove_poll'}) + state = updatePost(state, 1, {type: 'embed_add_poll'}) + + expect(state.thread.posts.map(post => post.embed.poll)).toEqual([ + undefined, + {statements: ['']}, + ]) + }) + + it('accepts a poll on another post once the post with one is removed', () => { + let state = updatePost(threadOfTwo(), 0, {type: 'embed_add_poll'}) + state = composerReducer(state, { + type: 'remove_post', + postId: state.thread.posts[0].id, + }) + state = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(state.thread.posts.map(post => post.embed.poll)).toEqual([ + {statements: ['']}, + ]) + }) + + it('still edits the poll that exists', () => { + let state = updatePost(threadOfTwo(), 0, {type: 'embed_add_poll'}) + state = updatePost(state, 0, { + type: 'embed_update_poll_statement', + index: 0, + text: 'first', + }) + state = updatePost(state, 0, {type: 'embed_add_poll_statement'}) + + expect(state.thread.posts[0].embed.poll).toEqual({ + statements: ['first', ''], + }) + }) + + it('keeps only the first poll of a restored draft', () => { + const posts = withPollOnEveryPost( + composerReducer(threadOfTwo(), {type: 'add_post'}), + ).thread.posts + const textOnly = { + ...posts[0], + embed: {...posts[0].embed, poll: undefined}, + } + const next = composerReducer(initialState(), { + type: 'restore_from_draft', + draftId: 'draft-1', + posts: [textOnly, posts[1], posts[2]], + threadgateAllow: undefined, + postgateEmbeddingRules: undefined, + loadedMedia: new Map(), + originalLocalRefs: new Set(), + }) + + expect(next.thread.posts.map(post => post.embed.poll)).toEqual([ + undefined, + {statements: ['statement 1']}, + undefined, + ]) + expect(next.thread.posts[0]).toBe(textOnly) + expect(next.thread.posts[1]).toBe(posts[1]) + }) +}) + +describe('assembly reference', () => { + it('stores the reference on the poll', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_update_poll_statement', index: 0, text: 'first'}, + {type: 'embed_set_poll_assembly', assembly: pendingRef}, + ]) + expect(post.embed.poll).toEqual({ + statements: ['first'], + assembly: pendingRef, + }) + }) + + it('replaces an earlier reference', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_set_poll_assembly', assembly: pendingRef}, + {type: 'embed_set_poll_assembly', assembly: createdRef}, + ]) + expect(post.embed.poll).toEqual({statements: [''], assembly: createdRef}) + }) + + it('stores the reference on the post it names', () => { + const state = updatePost(threadOfTwo(), 1, {type: 'embed_add_poll'}) + const next = updatePost(state, 1, { + type: 'embed_set_poll_assembly', + assembly: createdRef, + }) + + expect(next.thread.posts[0]).toBe(state.thread.posts[0]) + expect(next.thread.posts[1].embed.poll).toEqual({ + statements: [''], + assembly: createdRef, + }) + }) + + it('is ignored when the post has no poll', () => { + const state = initialState() + const next = updatePost(state, 0, { + type: 'embed_set_poll_assembly', + assembly: createdRef, + }) + + expect(next.thread.posts[0]).toBe(state.thread.posts[0]) + expect(next.thread.posts[0].embed.poll).toBeUndefined() + }) + + it('survives editing, adding and removing statements', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_set_poll_assembly', assembly: createdRef}, + {type: 'embed_update_poll_statement', index: 0, text: 'first'}, + {type: 'embed_add_poll_statement'}, + {type: 'embed_update_poll_statement', index: 1, text: 'second'}, + {type: 'embed_remove_poll_statement', index: 0}, + ]) + expect(post.embed.poll).toEqual({ + statements: ['second'], + assembly: createdRef, + }) + }) + + it('survives each statement action on its own', () => { + const seeded: PostAction[] = [ + {type: 'embed_add_poll'}, + {type: 'embed_add_poll_statement'}, + {type: 'embed_set_poll_assembly', assembly: createdRef}, + ] + expect( + draftAfter([ + ...seeded, + {type: 'embed_update_poll_statement', index: 1, text: 'edited'}, + ]).embed.poll, + ).toEqual({statements: ['', 'edited'], assembly: createdRef}) + expect( + draftAfter([...seeded, {type: 'embed_add_poll_statement'}]).embed.poll, + ).toEqual({statements: ['', '', ''], assembly: createdRef}) + expect( + draftAfter([...seeded, {type: 'embed_remove_poll_statement', index: 1}]) + .embed.poll, + ).toEqual({statements: [''], assembly: createdRef}) + }) + + it('goes away with the poll', () => { + const post = draftAfter([ + {type: 'embed_add_poll'}, + {type: 'embed_set_poll_assembly', assembly: createdRef}, + {type: 'embed_remove_poll'}, + {type: 'embed_add_poll'}, + ]) + expect(post.embed.poll).toEqual({statements: ['']}) + expect(post.embed.poll).not.toHaveProperty('assembly') + }) +}) + +describe('isPollAllowed', () => { + it.each([ + { + audience: 'a public post', + thread: threadWith({}), + replyTo: undefined, + expected: true, + }, + { + audience: 'a reply to a public post', + thread: threadWith({}), + replyTo: PUBLIC_POST, + expected: true, + }, + { + audience: 'a public-record feed', + thread: threadWith({ + communityFeed: publicRecordTarget, + communityFeedUri: publicRecordTarget.feed, + }), + replyTo: undefined, + expected: true, + }, + { + audience: 'a thread quoting a public post', + thread: threadQuoting('https://bsky.app/profile/alice.test/post/3kabc'), + replyTo: undefined, + expected: true, + }, + { + audience: 'Blacksky Only', + thread: threadWith({blackskyOnly: true}), + replyTo: undefined, + expected: false, + }, + { + audience: 'a private community space', + thread: threadWith({communitySpaceUri: SPACE}), + replyTo: undefined, + expected: false, + }, + { + audience: 'a feed backed by a space', + thread: threadWith({ + communityFeed: spaceTarget, + communityFeedUri: spaceTarget.feed, + }), + replyTo: undefined, + expected: false, + }, + { + audience: 'a public-record feed backed by a space', + thread: threadWith({ + communityFeed: { + ...publicRecordTarget, + config: {...publicRecordTarget.config, space: SPACE}, + }, + communityFeedUri: publicRecordTarget.feed, + }), + replyTo: undefined, + expected: false, + }, + { + audience: 'a community-record feed', + thread: threadWith({ + communityFeed: communityRecordTarget, + communityFeedUri: communityRecordTarget.feed, + }), + replyTo: undefined, + expected: false, + }, + { + audience: 'a feed that is not resolved yet', + thread: threadWith({communityFeedUri: publicRecordTarget.feed}), + replyTo: undefined, + expected: false, + }, + { + audience: 'a reply to a community post', + thread: threadWith({}), + replyTo: COMMUNITY_POST, + expected: false, + }, + { + audience: 'a reply to a space post', + thread: threadWith({}), + replyTo: SPACE_POST, + expected: false, + }, + { + audience: 'a thread quoting a community post', + thread: threadQuoting(COMMUNITY_POST_LINK), + replyTo: undefined, + expected: false, + }, + { + audience: 'a thread quoting a space post by its link', + thread: threadQuoting( + `https://bsky.app/profile/did:plc:author/post/3kabc?space=${encodeURIComponent(SPACE)}`, + ), + replyTo: undefined, + expected: false, + }, + { + audience: 'a thread quoting a space post by its record', + thread: threadQuoting(SPACE_POST), + replyTo: undefined, + expected: false, + }, + ])('is $expected for $audience', ({thread, replyTo, expected}) => { + expect(isPollAllowed(thread, replyTo)).toBe(expected) + }) +}) + +describe('isPublicTarget', () => { + it.each([ + {audience: 'a public post', thread: threadWith({}), expected: true}, + { + audience: 'a public-record feed', + thread: threadWith({ + communityFeed: publicRecordTarget, + communityFeedUri: publicRecordTarget.feed, + }), + expected: true, + }, + { + audience: 'a thread quoting a community post', + thread: threadQuoting(COMMUNITY_POST_LINK), + expected: true, + }, + { + audience: 'Blacksky Only', + thread: threadWith({blackskyOnly: true}), + expected: false, + }, + { + audience: 'a private community space', + thread: threadWith({communitySpaceUri: SPACE}), + expected: false, + }, + { + audience: 'a feed backed by a space', + thread: threadWith({ + communityFeed: spaceTarget, + communityFeedUri: spaceTarget.feed, + }), + expected: false, + }, + { + audience: 'a community-record feed', + thread: threadWith({ + communityFeed: communityRecordTarget, + communityFeedUri: communityRecordTarget.feed, + }), + expected: false, + }, + { + audience: 'a feed that is not resolved yet', + thread: threadWith({communityFeedUri: publicRecordTarget.feed}), + expected: false, + }, + ])('is $expected for $audience', ({thread, expected}) => { + expect(isPublicTarget(thread)).toBe(expected) + }) +}) + +const REMOVING: {change: string; action: ComposerAction}[] = [ + { + change: 'Blacksky Only is turned on', + action: {type: 'toggle_blacksky_only'}, + }, + { + change: 'Blacksky Only is selected', + action: {type: 'set_post_target', target: 'blacksky'}, + }, + { + change: 'a feed backed by a space is selected', + action: {type: 'set_post_target', target: spaceTarget}, + }, + { + change: 'a community-record feed is selected', + action: {type: 'set_post_target', target: communityRecordTarget}, + }, +] + +const KEEPING: {change: string; action: ComposerAction}[] = [ + { + change: 'the public target is selected', + action: {type: 'set_post_target', target: 'public'}, + }, + { + change: 'a public-record feed is selected', + action: {type: 'set_post_target', target: publicRecordTarget}, + }, +] + +describe('composer polls and post targets', () => { + it.each(REMOVING)( + 'removes polls from every post when $change', + ({action}) => { + const state = withPollOnEveryPost(threadOfTwo()) + const next = composerReducer(state, action) + + expect(threadHasPoll(state.thread)).toBe(true) + expect(isPollAllowed(next.thread, undefined)).toBe(false) + expect(next.thread.posts.map(post => post.embed.poll)).toEqual([ + undefined, + undefined, + ]) + expect(next.isDirty).toBe(true) + }, + ) + + it.each(KEEPING)('keeps the poll when $change', ({action}) => { + const state = apply(initialState(), [ + {type: 'embed_add_poll'}, + {type: 'embed_update_poll_statement', index: 0, text: 'keep'}, + {type: 'embed_set_poll_assembly', assembly: createdRef}, + ]) + const next = composerReducer(state, action) + + expect(next.thread.posts).toBe(state.thread.posts) + expect(next.thread.posts[0].embed.poll).toEqual({ + statements: ['keep'], + assembly: createdRef, + }) + }) + + it.each(KEEPING)( + 'keeps the poll when $change while another post quotes a community post', + ({action}) => { + const state = pollBesideCommunityQuote() + const next = composerReducer(state, action) + + expect(state.thread.posts[1].embed.quote).toEqual({ + type: 'link', + uri: COMMUNITY_POST_LINK, + }) + expect(isPollAllowed(next.thread, undefined)).toBe(false) + expect(next.thread.posts).toBe(state.thread.posts) + expect(next.thread.posts[0].embed.poll).toEqual({statements: ['keep']}) + }, + ) + + it.each(REMOVING)( + 'removes the poll when $change while another post quotes a community post', + ({action}) => { + const state = pollBesideCommunityQuote() + const next = composerReducer(state, action) + + expect(state.thread.posts[0].embed.poll).toEqual({statements: ['keep']}) + expect(next.thread.posts[0].embed.poll).toBeUndefined() + expect(next.thread.posts[1].embed.quote).toEqual({ + type: 'link', + uri: COMMUNITY_POST_LINK, + }) + }, + ) + + it('keeps the poll when Blacksky Only is turned off', () => { + const state = withPollOnEveryPost(initialState()) + state.thread.blackskyOnly = true + const next = composerReducer(state, {type: 'toggle_blacksky_only'}) + + expect(next.thread.blackskyOnly).toBe(false) + expect(next.thread.posts[0].embed.poll).toEqual({ + statements: ['statement 0'], + }) + }) + + it('leaves the other posts as they were when it removes a poll', () => { + const state = updatePost(threadOfTwo(), 1, {type: 'embed_add_poll'}) + const next = composerReducer(state, {type: 'toggle_blacksky_only'}) + + expect(next.thread.blackskyOnly).toBe(true) + expect(next.thread.posts[0]).toBe(state.thread.posts[0]) + expect(next.thread.posts[1].embed.poll).toBeUndefined() + expect(next.thread.posts[1].id).toBe(state.thread.posts[1].id) + }) + + it('keeps a pending video when it removes a poll', () => { + let state = updatePost(threadOfTwo(), 0, { + type: 'embed_add_video', + asset: {} as never, + abortController: new AbortController(), + }) + state = updatePost(state, 1, {type: 'embed_add_poll'}) + const media = state.thread.posts[0].embed.media + const next = composerReducer(state, {type: 'toggle_blacksky_only'}) + + expect(media?.type).toBe('video') + expect(next.thread.posts[0]).toBe(state.thread.posts[0]) + expect( + media?.type === 'video' && media.video.abortController.signal.aborted, + ).toBe(false) + expect(next.thread.posts[1].embed.poll).toBeUndefined() + }) + + it('removes a pending video and a poll when a space is selected', () => { + let state = updatePost(threadOfTwo(), 0, { + type: 'embed_add_video', + asset: {} as never, + abortController: new AbortController(), + }) + state = updatePost(state, 1, {type: 'embed_add_poll'}) + const media = state.thread.posts[0].embed.media + const next = composerReducer(state, { + type: 'set_post_target', + target: spaceTarget, + }) + + expect( + media?.type === 'video' && media.video.abortController.signal.aborted, + ).toBe(true) + expect(next.thread.posts[0].embed.media).toBeUndefined() + expect(next.thread.posts[1].embed.poll).toBeUndefined() + }) + + it.each(REMOVING)('refuses a new poll once $change', ({action}) => { + const state = composerReducer(initialState(), action) + const next = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(next).toBe(state) + expect(next.thread.posts[0].embed.poll).toBeUndefined() + }) + + it.each(KEEPING)('accepts a new poll once $change', ({action}) => { + const state = composerReducer(initialState(), action) + const next = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(next.thread.posts[0].embed.poll).toEqual({statements: ['']}) + }) + + it('refuses a new poll while another post quotes a community post', () => { + const state = updatePost(threadOfTwo(), 1, { + type: 'embed_add_uri', + uri: COMMUNITY_POST_LINK, + }) + const next = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(state.thread.posts[1].embed.quote).toEqual({ + type: 'link', + uri: COMMUNITY_POST_LINK, + }) + expect(next).toBe(state) + }) + + it('accepts a new poll once the target is public again', () => { + let state = composerReducer(initialState(), {type: 'toggle_blacksky_only'}) + state = composerReducer(state, {type: 'toggle_blacksky_only'}) + state = updatePost(state, 0, {type: 'embed_add_poll'}) + + expect(state.thread.blackskyOnly).toBe(false) + expect(state.thread.posts[0].embed.poll).toEqual({statements: ['']}) + }) +}) + +describe('isPollPostable', () => { + function pollPost(text: string, statements: string[]): PostDraft { + return { + ...draftAfter([ + {type: 'update_richtext', richtext: new RichText({text})}, + {type: 'embed_add_poll'}, + ]), + embed: { + quote: undefined, + media: undefined, + link: undefined, + poll: {statements}, + }, + } + } + + it.each([ + { + kind: 'text and distinct statements', + post: pollPost('Which one?', ['first', 'second']), + expected: true, + }, + { + kind: 'a single statement', + post: pollPost('Which one?', ['only']), + expected: true, + }, + { + kind: 'no text', + post: pollPost('', ['first', 'second']), + expected: false, + }, + { + kind: 'text that is only whitespace', + post: pollPost(' \n ', ['first', 'second']), + expected: false, + }, + { + kind: 'text with a null character', + post: pollPost('Which\u0000one?', ['first', 'second']), + expected: false, + }, + { + kind: 'a blank statement', + post: pollPost('Which one?', ['first', ' ']), + expected: false, + }, + { + kind: 'a repeated statement', + post: pollPost('Which one?', ['first', ' FIRST ']), + expected: false, + }, + { + kind: 'a statement over the limit', + post: pollPost('Which one?', ['a'.repeat(401)]), + expected: false, + }, + { + kind: 'more than ten statements', + post: pollPost( + 'Which one?', + [...Array(11).keys()].map(index => `statement ${index}`), + ), + expected: false, + }, + ])('is $expected for a poll with $kind', ({post, expected}) => { + expect(isPollPostable(post)).toBe(expected) + }) + + it('accepts post text longer than a topic, which is shortened', () => { + expect(isPollPostable(pollPost('a'.repeat(300), ['first']))).toBe(true) + }) + + it('is true for a post without a poll', () => { + expect(isPollPostable(draftAfter([]))).toBe(true) + }) + + it('is false when the poll shares the post with another attachment', () => { + const post = pollPost('Which one?', ['first']) + const link = {type: 'link' as const, uri: 'https://example.com/article'} + + expect(isPollPostable({...post, embed: {...post.embed, link}})).toBe(false) + expect(isPollPostable({...post, embed: {...post.embed, quote: link}})).toBe( + false, + ) + expect( + isPollPostable({ + ...post, + embed: {...post.embed, media: {type: 'gif', gif: {} as Gif, alt: ''}}, + }), + ).toBe(false) + }) +}) + +describe('post content predicates', () => { + it('treats a poll as an attachment and as content', () => { + const empty = draftAfter([]) + const withPoll = draftAfter([{type: 'embed_add_poll'}]) + expect(postHasAttachment(empty)).toBe(false) + expect(postHasContent(empty)).toBe(false) + expect(postHasAttachment(withPoll)).toBe(true) + expect(postHasContent(withPoll)).toBe(true) + }) +}) diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index eca87d6de..64aeedb5d 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -12,6 +12,15 @@ import { type CommunityFeedTarget, isSpaceBackedFeed, } from '#/lib/api/community-feed' +import {isCommunityPostUri} from '#/lib/api/community-post' +import { + type AssemblyRef, + isPollDraftPublishable, + isPollTopicPublishable, + POLL_MAX_STATEMENTS, + type PollDraft, +} from '#/lib/api/poll' +import {isSpacePostUrl} from '#/lib/api/space-permalink' import {type SelfLabel} from '#/lib/moderation' import {insertMentionAt} from '#/lib/strings/mention-manip' import {shortenLinks} from '#/lib/strings/rich-text-manip' @@ -72,6 +81,7 @@ export type EmbedDraft = { media: ImagesMedia | GalleryMedia | VideoMedia | GifMedia | undefined // This field may end up ignored if we have more important things to display than a link card: link: Link | undefined + poll?: PollDraft } export type PostDraft = { @@ -101,6 +111,34 @@ export type PostAction = | {type: 'embed_add_gif'; gif: Gif} | {type: 'embed_update_gif'; alt: string} | {type: 'embed_remove_gif'} + | {type: 'embed_add_poll'} + | {type: 'embed_update_poll_statement'; index: number; text: string} + | {type: 'embed_add_poll_statement'} + | {type: 'embed_remove_poll_statement'; index: number} + | {type: 'embed_set_poll_assembly'; assembly: AssemblyRef} + | {type: 'embed_remove_poll'} + +export function postHasAttachment(post: PostDraft): boolean { + return Boolean( + post.embed.media || post.embed.link || post.embed.quote || post.embed.poll, + ) +} + +export function postHasContent(post: PostDraft): boolean { + return post.richtext.text.trim().length > 0 || postHasAttachment(post) +} + +export function isPollPostable(post: PostDraft): boolean { + const poll = post.embed.poll + if (!poll) return true + return ( + isPollTopicPublishable(post.richtext.text) && + isPollDraftPublishable(poll) && + !post.embed.media && + !post.embed.link && + !post.embed.quote + ) +} export type ThreadDraft = { posts: PostDraft[] @@ -185,11 +223,63 @@ function hasSpaceVideoTarget(thread: ThreadDraft): boolean { ) } -function clearVideosOnTargetChange( +function isPublicFeedTarget(thread: ThreadDraft): boolean { + const feed = thread.communityFeed + if (!feed) { + // A feed known only by its URI is resolved at publish, so until then + // nothing shows that it is public. + return !thread.communityFeedUri + } + return ( + feed.config.contentType === 'publicRecord' && + !isSpaceBackedFeed(feed.config) + ) +} + +function isCommunityQuote(uri: string | undefined): boolean { + return isCommunityPostUri(uri) || isSpacePostUrl(uri) +} + +export function isPublicTarget(thread: ThreadDraft): boolean { + return ( + !thread.blackskyOnly && + !thread.communitySpaceUri && + isPublicFeedTarget(thread) + ) +} + +export function isPollAllowed( + thread: ThreadDraft, + replyTo: string | undefined, +): boolean { + return ( + isPublicTarget(thread) && + !isCommunityPostUri(replyTo) && + !thread.posts.some(post => isCommunityQuote(post.embed.quote?.uri)) + ) +} + +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) + return posts.map((post, index) => + post.embed.poll && index !== first + ? postReducer(post, {type: 'embed_remove_poll'}) + : post, + ) +} + +function applyTargetChange( state: ComposerState, nextThread: ThreadDraft, ): ComposerState { - if (hasSpaceVideoTarget(state.thread) === hasSpaceVideoTarget(nextThread)) { + const clearVideos = + hasSpaceVideoTarget(state.thread) !== hasSpaceVideoTarget(nextThread) + const clearPolls = threadHasPoll(nextThread) && !isPublicTarget(nextThread) + if (!clearVideos && !clearPolls) { return { ...state, isDirty: true, @@ -197,11 +287,15 @@ function clearVideosOnTargetChange( } } - const posts = state.thread.posts.map(post => - post.embed.media?.type === 'video' - ? postReducer(post, {type: 'embed_remove_video'}) - : post, - ) + const posts = state.thread.posts.map(post => { + const withoutVideo = + 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 + }) return { ...state, isDirty: true, @@ -268,7 +362,7 @@ export function composerReducer( communityFeedUri: undefined, communitySpaceUri: undefined, } - return clearVideosOnTargetChange( + return applyTargetChange( { ...state, }, @@ -284,7 +378,7 @@ export function composerReducer( communityFeedUri: typeof action.target === 'string' ? undefined : action.target.feed, } - return clearVideosOnTargetChange( + return applyTargetChange( { ...state, }, @@ -292,6 +386,12 @@ export function composerReducer( ) } case 'update_post': { + if ( + action.postAction.type === 'embed_add_poll' && + (threadHasPoll(state.thread) || !isPollAllowed(state.thread, undefined)) + ) { + return state + } let nextPosts = state.thread.posts const postIndex = state.thread.posts.findIndex( p => p.id === action.postId, @@ -393,7 +493,7 @@ export function composerReducer( loadedMediaMap: loadedMedia, originalLocalRefs, thread: { - posts, + posts: keepFirstPoll(posts), postgate: createPostgateRecord({ post: '', embeddingRules: postgateEmbeddingRules, @@ -443,7 +543,7 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_images': { - if (action.images.length === 0) { + if (action.images.length === 0 || state.embed.poll) { return state } const prevMedia = state.embed.media @@ -529,6 +629,9 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { return state } case 'embed_add_video': { + if (state.embed.poll) { + return state + } const prevMedia = state.embed.media let nextMedia = prevMedia if (!prevMedia) { @@ -579,6 +682,9 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_uri': { + if (state.embed.poll) { + return state + } const prevQuote = state.embed.quote const prevLink = state.embed.link let nextQuote = prevQuote @@ -626,6 +732,9 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_add_gif': { + if (state.embed.poll) { + return state + } const prevMedia = state.embed.media let nextMedia = prevMedia if (!prevMedia) { @@ -674,6 +783,87 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { }, } } + case 'embed_add_poll': { + if (postHasAttachment(state)) { + return state + } + return { + ...state, + embed: { + ...state.embed, + poll: {statements: ['']}, + }, + } + } + case 'embed_update_poll_statement': { + const poll = state.embed.poll + if (!poll || action.index < 0 || action.index >= poll.statements.length) { + return state + } + return { + ...state, + embed: { + ...state.embed, + poll: { + ...poll, + statements: poll.statements.map((text, i) => + i === action.index ? action.text : text, + ), + }, + }, + } + } + case 'embed_add_poll_statement': { + const poll = state.embed.poll + if (!poll || poll.statements.length >= POLL_MAX_STATEMENTS) { + return state + } + return { + ...state, + embed: { + ...state.embed, + poll: {...poll, statements: [...poll.statements, '']}, + }, + } + } + case 'embed_remove_poll_statement': { + const poll = state.embed.poll + if (!poll || poll.statements.length <= 1) { + return state + } + return { + ...state, + embed: { + ...state.embed, + poll: { + ...poll, + statements: poll.statements.filter((_, i) => i !== action.index), + }, + }, + } + } + case 'embed_set_poll_assembly': { + const poll = state.embed.poll + if (!poll) { + return state + } + return { + ...state, + embed: { + ...state.embed, + poll: {...poll, assembly: action.assembly}, + }, + } + } + case 'embed_remove_poll': { + return { + ...state, + embed: { + ...state.embed, + poll: undefined, + }, + } + } } }