@openpeepshq/rn-components 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/rn-components",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "React Native community screens and shared UI (extracted from the Black Ambition app) for the OpenPeeps stack.",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./src/index.ts",
@@ -142,8 +142,9 @@
142
142
  "timezones-list": "^3.1.0",
143
143
  "validator": "^13.15.23",
144
144
  "zustand": "^5.0.3",
145
- "@openpeepshq/common": "^0.9.0",
146
- "@openpeepshq/react": "^0.15.0"
145
+ "@openpeepshq/common": "^0.9.1",
146
+ "@openpeepshq/react": "^0.15.1",
147
+ "@openpeepshq/fetch-client": "^0.2.1"
147
148
  },
148
149
  "devDependencies": {
149
150
  "@babel/core": "^7.26.7",
@@ -0,0 +1,455 @@
1
+ /**
2
+ * Regression tests for #1813 — "buttons do not fit on screen, they go off to
3
+ * the right" (iPhone 11, 414pt). Three horizontal rows used an unbounded
4
+ * `justify-between` layout whose children could not shrink, so when their
5
+ * intrinsic width exceeded the row the rightmost control was pushed past the
6
+ * screen edge:
7
+ *
8
+ * - the feed event card's "View Event" button (post/types/Event.tsx),
9
+ * - the group card's "View" / join button (groups/GroupCard.tsx),
10
+ * - the mobile jam footer's "Leave" button (jams/JamFooter.tsx).
11
+ *
12
+ * The fix gives each row a shrinkable, truncating left side (`min-w-0 flex-1`
13
+ * + `numberOfLines={1}`) and an unsquishable right side (`shrink-0`), mirroring
14
+ * the web `GroupCard` and the `JamDesktopFooter` patterns already in this
15
+ * package. The shrinkable-left role applies to the variable-width text nodes
16
+ * themselves (the event date range, the group name), not just their row
17
+ * wrappers — in Yoga a text with `numberOfLines={1}` alone keeps its intrinsic
18
+ * width and can still push a `shrink-0` sibling off the right edge. These
19
+ * render tests pin those flex roles so the overflow class cannot return.
20
+ *
21
+ * All external modules are mocked (node jest env, no native modules); the host
22
+ * elements forward `className`/`numberOfLines` so the layout classes under
23
+ * test are readable on the rendered tree.
24
+ */
25
+ import { type ReactNode } from 'react';
26
+ import ReactTestRenderer from 'react-test-renderer';
27
+
28
+ const React = require('react');
29
+
30
+ const { mapColors } = require('../theme/defaults');
31
+
32
+ const el =
33
+ (tag: string, props?: Record<string, unknown>) =>
34
+ ({ children, ...rest }: { children?: ReactNode } & Record<string, unknown>) =>
35
+ React.createElement(tag, props ? { ...props, ...rest } : rest, children);
36
+
37
+ jest.mock('react-native', () => ({
38
+ View: el('View'),
39
+ Text: el('Text'),
40
+ Pressable: el('Pressable'),
41
+ }));
42
+
43
+ jest.mock('react-i18next', () => ({
44
+ useTranslation: () => ({
45
+ t: (_key: string, opts?: { defaultValue?: string }) =>
46
+ opts?.defaultValue ?? _key,
47
+ }),
48
+ }));
49
+
50
+ jest.mock('@react-navigation/native', () => ({
51
+ useNavigation: () => ({ navigate: jest.fn() }),
52
+ }));
53
+ jest.mock('@react-navigation/native-stack', () => ({}));
54
+
55
+ jest.mock('@openpeepshq/common', () => ({
56
+ formatBadgeCount: (n: number) => String(n),
57
+ isDeletedProfile: () => false,
58
+ }));
59
+ jest.mock('@openpeepshq/common/lib', () => ({
60
+ formatEventRecurrence: () => '',
61
+ }));
62
+
63
+ jest.mock('@openpeepshq/react', () => ({
64
+ useOpenpeeps: () => ({ queryClient: { invalidateQueries: jest.fn() } }),
65
+ useJamFooterControls: () => ({
66
+ isModerator: false,
67
+ isRecording: false,
68
+ recordingLabel: 'Record',
69
+ recordingEnabled: false,
70
+ busy: false,
71
+ sendReactionEmoji: jest.fn(),
72
+ toggleRecording: jest.fn(),
73
+ raiseHand: jest.fn(),
74
+ }),
75
+ // LeaveCloseButton context hooks (the real component is rendered in its own
76
+ // case below; JamFooter keeps its LeaveCloseButton element mock).
77
+ useJamContext: () => ({
78
+ jam: { moderators: [] },
79
+ jamPost: { id: 'jam-1' },
80
+ occurrence: undefined,
81
+ markIntentionalLeave: jest.fn(),
82
+ }),
83
+ useLeaveCloseJam: () => ({
84
+ busy: false,
85
+ confirmOpen: false,
86
+ setConfirmOpen: jest.fn(),
87
+ handleClick: jest.fn(),
88
+ handleLeave: jest.fn(),
89
+ handleClose: jest.fn(),
90
+ }),
91
+ // FollowUnfollowButton + profile/Avatar helpers (both render for real
92
+ // inside ProfileWithActionCard)
93
+ useFollowProfile: () => ({
94
+ isSelf: false,
95
+ isFollowing: false,
96
+ follow: jest.fn(),
97
+ unfollow: jest.fn(),
98
+ }),
99
+ hueFromHandle: () => 210,
100
+ initialsBackground: () => '#ddd',
101
+ svgCoverSrc: () => undefined,
102
+ getInitials: () => '',
103
+ }));
104
+
105
+ // Real theme defaults (nativewind-free), so useThemeOpacity color math runs
106
+ // as real code (same approach as JamRoomIndicators.test.tsx).
107
+ jest.mock('../theme/OpenPeepsThemeProvider', () => ({
108
+ useOpenPeepsTheme: () => ({
109
+ isDark: false,
110
+ colors: mapColors(false),
111
+ buttonRadius: '9999px',
112
+ refresh: () => {},
113
+ }),
114
+ }));
115
+
116
+ // `lib/utils` imports react-native-config (native module, ESM-only) — mock it
117
+ // wholesale with the helpers the components under test actually use.
118
+ jest.mock('../lib/utils', () => ({
119
+ cn: (...classes: (string | undefined)[]) => classes.filter(Boolean).join(' '),
120
+ formatEventDate: (_d?: unknown) => 'Jan 5',
121
+ }));
122
+
123
+ jest.mock('./ui/avatar', () => ({
124
+ Avatar: (props: Record<string, unknown>) =>
125
+ React.createElement('Avatar', props, props.children as never),
126
+ AvatarImage: () => null,
127
+ AvatarFallback: () => null,
128
+ }));
129
+ jest.mock('./ui/themed-text', () => ({
130
+ ThemedText: el('ThemedText', { forwarded: true }),
131
+ TextClassContext: {
132
+ Provider: ({ children }: { children?: ReactNode }) => children,
133
+ },
134
+ }));
135
+ jest.mock('./ui/button', () => ({
136
+ Button: el('Button', { forwarded: true }),
137
+ }));
138
+ // Default import (`import Toast from …`) in JamFooter /
139
+ // FollowUnfollowButton / JoinGroupButton — expose the `default` shape.
140
+ jest.mock('react-native-toast-message', () => ({
141
+ __esModule: true,
142
+ default: { show: jest.fn() },
143
+ }));
144
+ jest.mock('./icons/index', () => ({
145
+ UsersIcon: () => null,
146
+ UserXIcon: () => null,
147
+ CircleEllipsisIcon: () => null,
148
+ CircleStopIcon: () => null,
149
+ DiscIcon: () => null,
150
+ HandIcon: () => null,
151
+ InfoIcon: () => null,
152
+ LaughIcon: () => null,
153
+ MessageSquareTextIcon: () => null,
154
+ UsersRoundIcon: () => null,
155
+ }));
156
+
157
+ // The feed event card pulls the `custom/common` barrel (CachedImage,
158
+ // ParticipantAvatar), which transitively imports native modules unavailable in
159
+ // the node jest env — render them inert.
160
+ jest.mock('./custom/common/index', () => {
161
+ const React = require('react');
162
+ return {
163
+ CachedImage: (props: { children?: ReactNode }) =>
164
+ React.createElement('CachedImage', null, props.children),
165
+ };
166
+ });
167
+ jest.mock('./custom/common/participant-avatar', () => ({
168
+ ParticipantAvatar: () => null,
169
+ }));
170
+
171
+ jest.mock('./groups/JoinGroupButton', () => ({
172
+ JoinGroupButton: el('JoinGroupButton'),
173
+ }));
174
+ jest.mock('./jams/JamDeviceSelectors', () => ({
175
+ JamMicSelector: () => null,
176
+ JamCameraSelector: () => null,
177
+ JamAudioOutputSelector: () => null,
178
+ }));
179
+ jest.mock('./jams/JamReactionMenu', () => ({
180
+ JamReactionMenu: () => null,
181
+ }));
182
+ jest.mock('./jams/JamToolbarButton', () => ({
183
+ JamToolbarButton: el('JamToolbarButton'),
184
+ toneIconClass: {},
185
+ }));
186
+ const realLeaveCloseButton = jest.requireActual(
187
+ './jams/LeaveCloseButton'
188
+ ) as typeof import('./jams/LeaveCloseButton');
189
+ jest.mock('./jams/LeaveCloseButton', () => ({
190
+ ...realLeaveCloseButton,
191
+ // JamFooter renders the element mock; the dedicated case below renders
192
+ // LeaveCloseButton directly for the real component's guards.
193
+ LeaveCloseButton: el('LeaveCloseButton', { forwarded: true }),
194
+ }));
195
+
196
+ // LiveKit / the footer controls hook are irrelevant to the layout.
197
+ jest.mock('@livekit/react-native', () => ({
198
+ useParticipants: () => [],
199
+ useRoomContext: () => ({ disconnect: jest.fn() }),
200
+ }));
201
+
202
+ import { FeedEvent } from './post/types/Event';
203
+ import { GroupCard } from './groups/GroupCard';
204
+ import { JamFooter } from './jams/JamFooter';
205
+ import { ProfileWithActionCard } from './profile/ProfileWithActionCard';
206
+
207
+ // The real LeaveCloseButton, kept aside from its JamFooter element mock.
208
+ const { LeaveCloseButton: RealLeaveCloseButton } = realLeaveCloseButton;
209
+
210
+ type TreeNode = {
211
+ type: string;
212
+ props?: Record<string, unknown>;
213
+ children?: (string | TreeNode)[];
214
+ };
215
+
216
+ const walk = (node: TreeNode): TreeNode[] => [
217
+ node,
218
+ ...(node.children ?? [])
219
+ .filter((child): child is TreeNode => typeof child !== 'string')
220
+ .flatMap((child) => walk(child)),
221
+ ];
222
+
223
+ const find = (
224
+ node: TreeNode,
225
+ type: string,
226
+ prop: string
227
+ ): TreeNode | undefined =>
228
+ walk(node).find((n) => n.type === type && n.props && prop in n.props);
229
+
230
+ /** First element of `type` whose `className` contains every given token. */
231
+ const findWithClass = (
232
+ node: TreeNode,
233
+ type: string,
234
+ ...tokens: string[]
235
+ ): TreeNode | undefined =>
236
+ walk(node).find((n) => {
237
+ if (n.type !== type || typeof n.props?.className !== 'string') return false;
238
+ return tokens.every((t) => String(n.props!.className).includes(t));
239
+ });
240
+
241
+ const containsText = (node: TreeNode, text: string): boolean =>
242
+ walk(node).some((n) => {
243
+ if (typeof n.children === 'undefined') return false;
244
+ const joined = (n.children ?? [])
245
+ .map((c) => (typeof c === 'string' ? c : containsText(c, text)))
246
+ .filter(Boolean)
247
+ .join(' ');
248
+ return joined.includes(text);
249
+ });
250
+
251
+ const render = (ui: ReactNode): TreeNode => {
252
+ let tree!: ReactTestRenderer.ReactTestRenderer;
253
+ ReactTestRenderer.act(() => {
254
+ tree = ReactTestRenderer.create(ui);
255
+ });
256
+ expect(tree.toJSON()).not.toBeNull();
257
+ return tree.toJSON() as unknown as TreeNode;
258
+ };
259
+
260
+ describe('feed event card (post/types/Event.tsx)', () => {
261
+ const feedPost = {
262
+ id: 'post-1',
263
+ profile: { id: 'owner', displayName: 'Owner' },
264
+ visibility: 'public',
265
+ occurrenceStart: 'start',
266
+ occurrenceEnd: 'end',
267
+ data: { type: 'event', name: 'Meetup', timeZone: 'America/Chicago' },
268
+ };
269
+
270
+ test('long date range: date text truncates and the View Event button stays on-screen', () => {
271
+ const root = render(<FeedEvent post={feedPost as never} />);
272
+ expect(containsText(root, 'View Event')).toBe(true);
273
+
274
+ // The left date text is the shrinkable, truncating side of the row.
275
+ const dateText = find(root, 'ThemedText', 'numberOfLines');
276
+ expect(dateText).toBeDefined();
277
+ expect(dateText!.props?.numberOfLines).toBe(1);
278
+ expect(String(dateText!.props?.className)).toContain(
279
+ 'text-muted-foreground'
280
+ );
281
+ // `numberOfLines` alone does not yield width in Yoga — the text must also
282
+ // be shrinkable, or a long date range pushes the button off-screen again.
283
+ expect(String(dateText!.props?.className)).toContain('min-w-0');
284
+ expect(String(dateText!.props?.className)).toContain('flex-1');
285
+
286
+ // The "View Event" button is the unsquishable right-hand control: it keeps
287
+ // its own width instead of being pushed off the right edge.
288
+ const button = find(root, 'Button', 'onPress');
289
+ expect(button).toBeDefined();
290
+ expect(String(button!.props?.className)).toContain('shrink-0');
291
+ });
292
+
293
+ test('event without an end time still keeps the guard on the button', () => {
294
+ const root = render(
295
+ <FeedEvent post={{ ...feedPost, occurrenceEnd: undefined } as never} />
296
+ );
297
+ const button = find(root, 'Button', 'onPress');
298
+ expect(button).toBeDefined();
299
+ expect(String(button!.props?.className)).toContain('shrink-0');
300
+ });
301
+ });
302
+
303
+ describe('group card (groups/GroupCard.tsx)', () => {
304
+ const group = {
305
+ id: 'g-1',
306
+ name: 'A very long group name that will never fit on one narrow row',
307
+ displayName: 'A very long group name that will never fit on one narrow row',
308
+ membersCount: 42,
309
+ avatar: undefined,
310
+ };
311
+
312
+ test('long group name: name truncates and the action stays on-screen', () => {
313
+ const root = render(
314
+ <GroupCard
315
+ group={group as never}
316
+ isGroupMember
317
+ handleViewGroup={() => {}}
318
+ />
319
+ );
320
+
321
+ // The group name is the shrinkable, truncating side of the inner name row
322
+ // (next to the fixed-width unread badge): it yields width and ellipsizes
323
+ // instead of pushing the badge or the action column off the card.
324
+ const name = findWithClass(
325
+ root,
326
+ 'ThemedText',
327
+ 'min-w-0',
328
+ 'flex-1',
329
+ 'font-semibold'
330
+ );
331
+ expect(name).toBeDefined();
332
+ expect(name!.props?.numberOfLines).toBe(1);
333
+ // The component renders the display name itself (no truncateText
334
+ // pre-truncation), so the full string must be present on the tree.
335
+ expect(
336
+ containsText(root, 'A very long group name that will never fit')
337
+ ).toBe(true);
338
+
339
+ // The action column (View / join) is unsquishable, so it never gets pushed
340
+ // off the right edge.
341
+ const action = findWithClass(root, 'View', 'shrink-0', 'ml-2');
342
+ expect(action).toBeDefined();
343
+ });
344
+
345
+ test('non-member: the action column keeps the shrink guard', () => {
346
+ const root = render(
347
+ <GroupCard
348
+ group={group as never}
349
+ isGroupMember={false}
350
+ handleViewGroup={() => {}}
351
+ />
352
+ );
353
+ // The join control renders, and its action column is still unsquishable.
354
+ const join = [...walk(root)].find((n) => n.type === 'JoinGroupButton');
355
+ expect(join).toBeDefined();
356
+ const action = findWithClass(root, 'View', 'shrink-0', 'ml-2');
357
+ expect(action).toBeDefined();
358
+ });
359
+ });
360
+
361
+ describe('mobile jam footer (jams/JamFooter.tsx)', () => {
362
+ const props = {
363
+ chatOpen: false,
364
+ onToggleChat: () => {},
365
+ peopleOpen: false,
366
+ onTogglePeople: () => {},
367
+ detailsOpen: false,
368
+ onToggleDetails: () => {},
369
+ speakerEnabled: true,
370
+ onSpeakerChange: () => {},
371
+ onToggleSpeaker: () => {},
372
+ };
373
+
374
+ test('device group can yield width; the Leave cluster is fixed', () => {
375
+ const root = render(<JamFooter {...(props as never)} />);
376
+
377
+ const views = [...walk(root)]
378
+ .filter(
379
+ (n) => n.type === 'View' && typeof n.props?.className === 'string'
380
+ )
381
+ .map((n) => String(n.props?.className));
382
+ expect(views.length).toBeGreaterThanOrEqual(2);
383
+
384
+ // The left device-selector group is the shrinkable side of the footer row
385
+ // and clips (never overflows onto) the fixed right cluster.
386
+ const left = views.find(
387
+ (c) => c.includes('min-w-0') && c.includes('flex-1')
388
+ );
389
+ expect(left).toBeDefined();
390
+ expect(left).toContain('overflow-hidden');
391
+
392
+ // The reactions / overflow / Leave cluster is the unsquishable side, so
393
+ // "Leave" can never be pushed past the screen edge.
394
+ const right = views.find((c) => c.includes('shrink-0'));
395
+ expect(right).toBeDefined();
396
+
397
+ // The Leave control is present in the fixed cluster.
398
+ const leave = [...walk(root)].find((n) => n.type === 'LeaveCloseButton');
399
+ expect(leave).toBeDefined();
400
+ });
401
+ });
402
+
403
+ // The real Leave button (round-3 suggestion 4): the JamFooter case mocks this
404
+ // component, so its own guards are pinned here — its context hooks are mocked
405
+ // alongside the other @openpeepshq/react hooks at the top of the file, so it
406
+ // renders without native modules and its Button / text props stay readable.
407
+ describe('real leave/close button (jams/LeaveCloseButton.tsx)', () => {
408
+ test('the Leave label is unsquishable and never wraps', () => {
409
+ const root = render(<RealLeaveCloseButton />);
410
+
411
+ const button = find(root, 'Button', 'onPress');
412
+ expect(button).toBeDefined();
413
+ expect(String(button!.props?.className)).toContain('shrink-0');
414
+ const label = find(root, 'ThemedText', 'numberOfLines');
415
+ expect(label).toBeDefined();
416
+ expect(label!.props?.numberOfLines).toBe(1);
417
+ expect(containsText(root, 'jams.exit.confirm')).toBe(true);
418
+ });
419
+ });
420
+
421
+ // Same overflow class in the profile rows with a trailing follow/unfollow
422
+ // button (round-3 suggestion 1): the card renders at full sheet width in
423
+ // RepostModal/ReactionsModal, so a long name/handle must shrink and truncate
424
+ // instead of pushing the button past the right edge.
425
+ describe('profile with action card (profile/ProfileWithActionCard.tsx)', () => {
426
+ const profile = {
427
+ did: 'did:plc:test',
428
+ handle: 'grace.hopper@example',
429
+ displayName:
430
+ 'A very long display name that will never fit on one narrow row',
431
+ } as never;
432
+
433
+ test('long name: texts truncate and the follow button stays on-screen', () => {
434
+ const root = render(<ProfileWithActionCard profile={profile} />);
435
+
436
+ // The name/handle texts are the shrinkable, truncating side of the row.
437
+ const name = findWithClass(root, 'ThemedText', 'font-bold');
438
+ expect(name).toBeDefined();
439
+ expect(name!.props?.numberOfLines).toBe(1);
440
+ const texts = [...walk(root)].filter((n) => n.type === 'ThemedText');
441
+ expect(
442
+ texts.some((n) => String(n.props?.numberOfLines ?? '') === '1')
443
+ ).toBe(true);
444
+
445
+ // The text column yields width; the follow button never leaves the edge.
446
+ const column = findWithClass(root, 'View', 'min-w-0', 'flex-1');
447
+ expect(column).toBeDefined();
448
+ const action = findWithClass(root, 'View', 'shrink-0');
449
+ expect(action).toBeDefined();
450
+ // FollowUnfollowButton renders for real (its hooks are mocked at the top
451
+ // of the file); its unsquishable wrapper column is the pinned contract.
452
+ const actionButton = findWithClass(action!, 'Button');
453
+ expect(actionButton).toBeDefined();
454
+ });
455
+ });
@@ -4,7 +4,6 @@ import { formatBadgeCount, GroupWithMeta } from '@openpeepshq/common';
4
4
  import { useOpenpeeps } from '@openpeepshq/react';
5
5
  import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar';
6
6
  import { ThemedText } from '../ui/themed-text';
7
- import { truncateText } from '../../lib/utils';
8
7
  import { Button } from '../ui/button';
9
8
  import { UsersIcon } from '../icons/index';
10
9
  import { useTranslation } from 'react-i18next';
@@ -27,12 +26,12 @@ export const GroupCard = ({
27
26
  const { t } = useTranslation();
28
27
 
29
28
  return (
30
- <View className="flex flex-row justify-between w-full mb-8">
29
+ <View className="flex flex-row items-center justify-between w-full mb-8">
31
30
  <Pressable
32
31
  onPress={handleViewGroup}
33
- className="flex flex-row items-center gap-x-2"
32
+ className="flex min-w-0 flex-1 flex-row items-center gap-x-2"
34
33
  >
35
- <Avatar alt="profile" className="size-16">
34
+ <Avatar alt="profile" className="size-16 shrink-0">
36
35
  {group?.avatar ? (
37
36
  <AvatarImage
38
37
  source={{
@@ -45,10 +44,13 @@ export const GroupCard = ({
45
44
  </AvatarFallback>
46
45
  )}
47
46
  </Avatar>
48
- <View className="ml-2">
47
+ <View className="ml-2 min-w-0 flex-1">
49
48
  <View className="flex-row items-center gap-x-2">
50
- <ThemedText className="text-lg font-semibold">
51
- {truncateText(group.displayName, 25) || '-'}
49
+ <ThemedText
50
+ className="min-w-0 flex-1 text-lg font-semibold"
51
+ numberOfLines={1}
52
+ >
53
+ {group.displayName || '-'}
52
54
  </ThemedText>
53
55
  {unreadCount > 0 ? (
54
56
  <View className="bg-destructive size-5 min-w-5 shrink-0 items-center justify-center rounded-full px-1">
@@ -59,26 +61,27 @@ export const GroupCard = ({
59
61
  ) : null}
60
62
  </View>
61
63
  <View className="flex-row gap-x-3 mt-2 items-center">
62
- <ThemedText className="text-sm">
63
- {group?.membersCount} Member
64
- {group?.membersCount && group?.membersCount > 1 ? 's' : ''}
64
+ <ThemedText className="text-sm" numberOfLines={1}>
65
+ {t('groups.members.count', { count: group?.membersCount ?? 0 })}
65
66
  </ThemedText>
66
67
  </View>
67
68
  </View>
68
69
  </Pressable>
69
- {!isGroupMember ? (
70
- <JoinGroupButton
71
- group={group}
72
- onJoined={async () => {
73
- await queryClient.invalidateQueries();
74
- handleViewGroup();
75
- }}
76
- />
77
- ) : (
78
- <Button variant="outline" onPress={handleViewGroup}>
79
- <ThemedText>{t('groups.actions.view')}</ThemedText>
80
- </Button>
81
- )}
70
+ <View className="flex shrink-0 ml-2">
71
+ {!isGroupMember ? (
72
+ <JoinGroupButton
73
+ group={group}
74
+ onJoined={async () => {
75
+ await queryClient.invalidateQueries();
76
+ handleViewGroup();
77
+ }}
78
+ />
79
+ ) : (
80
+ <Button variant="outline" onPress={handleViewGroup}>
81
+ <ThemedText>{t('groups.actions.view')}</ThemedText>
82
+ </Button>
83
+ )}
84
+ </View>
82
85
  </View>
83
86
  );
84
87
  };
@@ -33,8 +33,13 @@ export const JoinGroupButton = ({ group, onJoined }: JoinGroupButtonProps) => {
33
33
  };
34
34
 
35
35
  return (
36
- <Button variant="outline" disabled={submitting} onPress={onPress}>
37
- <ThemedText>
36
+ <Button
37
+ variant="outline"
38
+ disabled={submitting}
39
+ onPress={onPress}
40
+ className="shrink-0"
41
+ >
42
+ <ThemedText numberOfLines={1}>
38
43
  {submitting ? t('common.states.loading') : t('groups.join.submit')}
39
44
  </ThemedText>
40
45
  </Button>
@@ -7,11 +7,12 @@ import { useCurrentProfile, useRouter } from '@openpeepshq/react';
7
7
  import { Button } from '../ui/button';
8
8
  import { ThemedText } from '../ui/themed-text';
9
9
  import { EventRsvpButton } from '../post/pieces/EventRsvpButton';
10
+ import { JamGuestForm } from './JamGuestForm';
10
11
  import { JamRoomPanel, JamRoomPanelLink } from './JamRoomPanel';
11
12
 
12
13
  export interface JamCapacityGateProps {
13
14
  jamPost: PublicPost;
14
- reason: 'full' | 'rsvp-required' | 'removed';
15
+ reason: 'full' | 'rsvp-required' | 'removed' | 'guest-required';
15
16
  eventName?: string;
16
17
  occurrence?: string;
17
18
  }
@@ -26,6 +27,13 @@ export const JamCapacityGate = ({
26
27
  const me = useCurrentProfile();
27
28
  const router = useRouter();
28
29
  const eventData = jamPost.data?.type === 'event' ? jamPost.data : undefined;
30
+
31
+ // Signed-out visitor on a waiting-room jam: the join POST refuses anonymous
32
+ // requests, so gate on the guest-pass form before they can queue.
33
+ if (reason === 'guest-required' && !me) {
34
+ return <JamGuestForm />;
35
+ }
36
+
29
37
  const showRsvp =
30
38
  (reason === 'rsvp-required' || reason === 'full') &&
31
39
  !!me &&
@@ -216,31 +216,35 @@ export const JamFooter = ({
216
216
  />
217
217
  ) : null}
218
218
 
219
- <JamMicSelector />
220
- <JamCameraSelector />
221
- <JamAudioOutputSelector
222
- speakerDeviceId={speakerDeviceId}
223
- speakerEnabled={speakerEnabled}
224
- onSpeakerChange={onSpeakerChange}
225
- onToggleSpeaker={onToggleSpeaker}
226
- />
219
+ <View className="flex min-w-0 flex-1 flex-row items-center gap-x-2 overflow-hidden">
220
+ <JamMicSelector />
221
+ <JamCameraSelector />
222
+ <JamAudioOutputSelector
223
+ speakerDeviceId={speakerDeviceId}
224
+ speakerEnabled={speakerEnabled}
225
+ onSpeakerChange={onSpeakerChange}
226
+ onToggleSpeaker={onToggleSpeaker}
227
+ />
228
+ </View>
227
229
 
228
- <JamToolbarButton
229
- title={t('jams.reactions.sendTitle')}
230
- tone={reactionTone}
231
- action={() => setReactionMenuOpen((open) => !open)}
232
- >
233
- <LaughIcon size={20} className={toneIconClass[reactionTone]} />
234
- </JamToolbarButton>
230
+ <View className="flex shrink-0 flex-row items-center gap-x-2">
231
+ <JamToolbarButton
232
+ title={t('jams.reactions.sendTitle')}
233
+ tone={reactionTone}
234
+ action={() => setReactionMenuOpen((open) => !open)}
235
+ >
236
+ <LaughIcon size={20} className={toneIconClass[reactionTone]} />
237
+ </JamToolbarButton>
235
238
 
236
- <JamToolbarButton
237
- title={t('jams.drawer.jamControls')}
238
- action={() => setMobileMenuOpen((open) => !open)}
239
- >
240
- <CircleEllipsisIcon size={20} className="text-foreground" />
241
- </JamToolbarButton>
239
+ <JamToolbarButton
240
+ title={t('jams.drawer.jamControls')}
241
+ action={() => setMobileMenuOpen((open) => !open)}
242
+ >
243
+ <CircleEllipsisIcon size={20} className="text-foreground" />
244
+ </JamToolbarButton>
242
245
 
243
- <LeaveCloseButton />
246
+ <LeaveCloseButton />
247
+ </View>
244
248
  </View>
245
249
  );
246
250
  };
@@ -3,7 +3,8 @@ import { ScrollView, View } from 'react-native';
3
3
  import { useParticipants, useRoomContext } from '@livekit/react-native';
4
4
  import type { Participant } from 'livekit-client';
5
5
  import { useTranslation } from 'react-i18next';
6
- import { profileName } from '@openpeepshq/common/lib';
6
+ import { profileName, waitingRoomEntryName } from '@openpeepshq/common/lib';
7
+ import type { JamWaitingProfile } from '@openpeepshq/common';
7
8
  import { parseParticipantMetadata, useJamPeople } from '@openpeepshq/react';
8
9
  import {
9
10
  AudioLinesIcon,
@@ -158,9 +159,9 @@ export const JamPeopleDrawer = ({ open, onClose }: JamPeopleDrawerProps) => {
158
159
  className="flex-row items-center justify-between gap-2"
159
160
  >
160
161
  <View className="min-w-0 flex-1 flex-row items-center gap-2">
161
- <ProfileAvatar profile={profile} className="size-8" />
162
+ <WaitingRoomAvatar profile={profile} />
162
163
  <ThemedText numberOfLines={1} className="shrink text-sm">
163
- {profileName(profile)}
164
+ {waitingRoomEntryName(profile)}
164
165
  </ThemedText>
165
166
  </View>
166
167
  <Button
@@ -181,3 +182,18 @@ export const JamPeopleDrawer = ({ open, onClose }: JamPeopleDrawerProps) => {
181
182
  </JamDrawer>
182
183
  );
183
184
  };
185
+
186
+ /**
187
+ * Waiting-room entries carry only a display name (no avatar/handle), so the
188
+ * initials fallback renders a stable, honest placeholder.
189
+ */
190
+ function WaitingRoomAvatar({ profile }: { profile: JamWaitingProfile }) {
191
+ // Initials-avatar input: only the name matters, so narrow instead of
192
+ // widening a queue entry to a full Profile.
193
+ return (
194
+ <ProfileAvatar
195
+ profile={{ displayName: waitingRoomEntryName(profile) }}
196
+ className="size-8"
197
+ />
198
+ );
199
+ }
@@ -1,10 +1,12 @@
1
- import React, { useState } from 'react';
1
+ import React, { useCallback, useState } from 'react';
2
2
  import { View } from 'react-native';
3
3
  import { useTranslation } from 'react-i18next';
4
4
  import {
5
+ apiErrorMessage,
5
6
  type JamJoinParams,
6
7
  useJoinWaitingRoomToken,
7
8
  } from '@openpeepshq/react';
9
+ import type { SseError } from '@openpeepshq/fetch-client';
8
10
  import { Button } from '../ui/button';
9
11
  import { ThemedText } from '../ui/themed-text';
10
12
 
@@ -17,8 +19,33 @@ const JamWaitingRoomListener = ({
17
19
  }: {
18
20
  onJoin: JamRequestJoinProps['onJoin'];
19
21
  }) => {
20
- useJoinWaitingRoomToken(onJoin);
21
- return null;
22
+ const { t } = useTranslation();
23
+ const [error, setError] = useState<string | null>(null);
24
+
25
+ // The error state is not terminal: when the token is delivered (a fresh
26
+ // stream after a reconnection or a moderator admission), the stale error
27
+ // must not sit behind the recovered stream.
28
+ const joinAndClearError = useCallback(
29
+ (params: JamJoinParams) => {
30
+ setError(null);
31
+ onJoin(params);
32
+ },
33
+ [onJoin]
34
+ );
35
+
36
+ useJoinWaitingRoomToken(joinAndClearError, (e?: SseError) => {
37
+ // Reuse the shared key→message mapping (`errorKey ?? key`, translate
38
+ // `error.*` keys). The SSE path passes an empty fallback so a keyless,
39
+ // message-less error renders nothing rather than a generic "Error".
40
+ const message = apiErrorMessage(e, t, '');
41
+ setError(message.length > 0 ? message : null);
42
+ });
43
+
44
+ return error ? (
45
+ <ThemedText className="text-center text-sm text-destructive">
46
+ {error}
47
+ </ThemedText>
48
+ ) : null;
22
49
  };
23
50
 
24
51
  export const JamRequestJoin = ({ onJoin }: JamRequestJoinProps) => {
@@ -51,8 +51,12 @@ export const LeaveCloseButton = () => {
51
51
  accessibilityLabel={t('jams.exit.confirm')}
52
52
  disabled={busy}
53
53
  onPress={handleClick}
54
+ className="shrink-0"
54
55
  >
55
- <ThemedText className="text-sm text-destructive-foreground">
56
+ <ThemedText
57
+ className="text-sm text-destructive-foreground"
58
+ numberOfLines={1}
59
+ >
56
60
  {t('jams.exit.confirm')}
57
61
  </ThemedText>
58
62
  </Button>
@@ -32,8 +32,11 @@ export const FeedEvent = ({ post }: { post: PublicPost }) => {
32
32
  </View>
33
33
  )}
34
34
 
35
- <View className="flex-row items-center justify-between">
36
- <ThemedText className="text-muted-foreground text-sm">
35
+ <View className="flex-row items-center justify-between gap-x-2">
36
+ <ThemedText
37
+ className="min-w-0 flex-1 text-muted-foreground text-sm"
38
+ numberOfLines={1}
39
+ >
37
40
  {formatEventDate(start)}
38
41
  {end && ` - ${formatEventDate(end)}`}
39
42
  {eventData.timeZone && ` (${eventData.timeZone})`}
@@ -41,6 +44,7 @@ export const FeedEvent = ({ post }: { post: PublicPost }) => {
41
44
  <Button
42
45
  variant="outline"
43
46
  size="sm"
47
+ className="shrink-0"
44
48
  onPress={() => navigation.navigate('Post', { id: post.id })}
45
49
  >
46
50
  <ThemedText className="text-xs">
@@ -28,7 +28,10 @@ export const ProfileAvatar = ({
28
28
  profile,
29
29
  className,
30
30
  }: {
31
- profile: Profile;
31
+ /** `Profile`-shaped; only `displayName`/`handle`/`avatar` are read. */
32
+ profile: Partial<
33
+ Pick<Profile, 'displayName' | 'handle' | 'avatar' | 'deletedAt'>
34
+ >;
32
35
  className?: string;
33
36
  }) => {
34
37
  const { t } = useTranslation();
@@ -16,20 +16,28 @@ export const ProfileWithActionCard = ({
16
16
  leading,
17
17
  }: ProfileWithActionCardProps) => (
18
18
  <View className="mb-4 w-full flex-row items-center justify-between">
19
- <View className="flex-row items-center gap-2">
19
+ <View className="flex min-w-0 flex-1 flex-row items-center gap-2">
20
20
  {leading}
21
- <ProfileLink profile={profile} className="flex-row items-center gap-2">
21
+ <ProfileLink
22
+ profile={profile}
23
+ className="flex min-w-0 flex-1 flex-row items-center gap-2"
24
+ >
22
25
  <ProfileAvatar profile={profile} />
23
- <View>
24
- <ThemedText className="font-bold">
26
+ <View className="min-w-0 flex-1">
27
+ <ThemedText className="font-bold" numberOfLines={1}>
25
28
  {profile.displayName || profile.handle}
26
29
  </ThemedText>
27
- <ThemedText className="text-sm text-muted-foreground">
30
+ <ThemedText
31
+ className="text-sm text-muted-foreground"
32
+ numberOfLines={1}
33
+ >
28
34
  @{profile.handle}
29
35
  </ThemedText>
30
36
  </View>
31
37
  </ProfileLink>
32
38
  </View>
33
- <FollowUnfollowButton profile={profile} compact />
39
+ <View className="shrink-0">
40
+ <FollowUnfollowButton profile={profile} compact />
41
+ </View>
34
42
  </View>
35
43
  );
package/src/lib/post.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { PollChoiceForm } from '../types';
2
- import Toast from 'react-native-toast-message';
3
1
  import {
4
2
  dateSorter,
5
3
  MediaAttachmentData,
@@ -7,7 +5,6 @@ import {
7
5
  PublicPost,
8
6
  Thread,
9
7
  } from '@openpeepshq/common';
10
- import { uploadMedia } from './uploadMedia';
11
8
 
12
9
  /** True if the attachment is still being processed server-side. */
13
10
  export const isAttachmentProcessing = (
@@ -19,131 +16,6 @@ export const hasProcessingAttachments = (
19
16
  postData: PostCreationData | undefined
20
17
  ): boolean => (postData?.data?.attachments ?? []).some(isAttachmentProcessing);
21
18
 
22
- export const handleMediaUpload = async (
23
- selectedMedia: { uri: string; type: 'video' | 'image'; alt?: string }[],
24
- createAttachments: any,
25
- serverConfig: string
26
- ) => {
27
- const attachments = await Promise.all(
28
- selectedMedia.map((media) =>
29
- uploadMedia({
30
- mediaUri: media.uri,
31
- createAttachments: createAttachments,
32
- type: media.type,
33
- usage: `${serverConfig}:${media.type}`,
34
- alt: media?.alt,
35
- })
36
- )
37
- );
38
-
39
- return attachments.filter(
40
- (attachment): attachment is NonNullable<typeof attachment> =>
41
- attachment !== null
42
- );
43
- };
44
-
45
- export const validatePollData = (formData: PollChoiceForm): boolean => {
46
- if (formData.choices.some((choice) => !choice.text.trim())) {
47
- Toast.show({
48
- type: 'error',
49
- text1: 'Please fill in all poll choices',
50
- });
51
- return false;
52
- }
53
-
54
- if (!formData.pollLength.trim()) {
55
- Toast.show({
56
- type: 'error',
57
- text1: 'Please set a poll length',
58
- });
59
- return false;
60
- }
61
- return true;
62
- };
63
-
64
- export const noteToQuestion = (
65
- postData: PostCreationData
66
- ): PostCreationData => ({
67
- ...postData,
68
- type: 'question',
69
- data: {
70
- ...postData.data,
71
- type: 'question',
72
- options: [
73
- {
74
- type: 'note',
75
- content: '',
76
- },
77
- {
78
- type: 'note',
79
- content: '',
80
- },
81
- ],
82
- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString(),
83
- },
84
- });
85
- export const toQuestion = (postData: PostCreationData): PostCreationData => ({
86
- ...postData,
87
- type: 'question',
88
- data: {
89
- ...postData.data,
90
- type: 'question',
91
- options: [
92
- {
93
- type: 'note',
94
- content: '',
95
- },
96
- {
97
- type: 'note',
98
- content: '',
99
- },
100
- ],
101
- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString(),
102
- },
103
- });
104
-
105
- export const toArticle = (postData: PostCreationData): PostCreationData => ({
106
- ...postData,
107
- type: 'article',
108
- data: {
109
- content: postData.data.content,
110
- type: 'article',
111
- attachments: postData.data.attachments,
112
- },
113
- });
114
-
115
- export const toNote = (postData: PostCreationData): PostCreationData => ({
116
- ...postData,
117
- type: 'note',
118
- data: {
119
- content: postData.data.content,
120
- type: 'note',
121
- attachments: postData.data.attachments,
122
- },
123
- });
124
-
125
- export const questionToNote = (
126
- postData: PostCreationData
127
- ): PostCreationData => ({
128
- ...postData,
129
- type: 'note',
130
- data: {
131
- content: postData.data.content,
132
- type: 'note',
133
- attachments: postData.data.attachments,
134
- },
135
- });
136
-
137
- // export const handleScroll = (
138
- // event: any,
139
- // setCurrentIndex: (index: number) => void,
140
- // ) => {
141
- // const slideSize = event.nativeEvent.layoutMeasurement.width;
142
- // const offset = event.nativeEvent.contentOffset.x;
143
- // const currentIndex = Math.round(offset / slideSize);
144
- // setCurrentIndex(currentIndex);
145
- // };
146
-
147
19
  export const lastLongestPathSelector = (
148
20
  thread: Thread
149
21
  ): Thread & { depth: number } => {
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Regression coverage for #1799 (native composer) — the poll <-> note type
3
+ * switch must carry the typed text over *and* persist the converted draft to
4
+ * the app-lifetime local post store, so the carry-over (including the
5
+ * `questionDraft` stash that lets a later note -> poll restore the original
6
+ * poll) survives a screen unmount/remount.
7
+ *
8
+ * The native `NewPost` is a large composite, so every external import is
9
+ * mocked (node jest env, no native modules) — mirroring FullEvent.test.tsx.
10
+ * Only `handleSelectComposerType` is exercised; the surrounding form / footer
11
+ * / picker UI render inert mocks. The shared `toNote`/`toQuestion`/
12
+ * `isSwitchablePostData` helpers are loaded from `@openpeepshq/react`'s
13
+ * real source so the conversion logic under test is the production one.
14
+ */
15
+ import { type ReactNode } from 'react';
16
+ import ReactTestRenderer from 'react-test-renderer';
17
+
18
+ const React = require('react');
19
+
20
+ // Shared helper (the production conversion logic) resolved from the real
21
+ // react package source. The jest moduleNameMapper only pins the package
22
+ // *root* import to contentLength; this explicit subpath keeps real toNote /
23
+ // toQuestion / isSwitchablePostData in the test.
24
+ const mockSharedPost = require('../../../../react/src/lib/post');
25
+
26
+ // --- react-native: host elements render as plain host tags ----------------
27
+ jest.mock('react-native', () => {
28
+ const make = (tag: string) => (props: { children?: ReactNode }) =>
29
+ React.createElement(tag, null, props.children);
30
+ return { View: make('View'), Text: make('Text') };
31
+ });
32
+
33
+ // --- i18n: resolve keys to their defaultValue -----------------------------
34
+ jest.mock('react-i18next', () => ({
35
+ useTranslation: () => ({
36
+ t: (_key: string, opts?: { defaultValue?: string; number?: number }) =>
37
+ opts?.defaultValue ?? _key,
38
+ }),
39
+ }));
40
+
41
+ // --- shared @openpeepshq/react: real conversion helpers, inert context ----
42
+ jest.mock('@openpeepshq/react', () => ({
43
+ isSwitchablePostData: mockSharedPost.isSwitchablePostData,
44
+ toNote: mockSharedPost.toNote,
45
+ toQuestion: mockSharedPost.toQuestion,
46
+ useOpenpeeps: () => ({
47
+ currentProfile: { id: 'me', roles: [] },
48
+ openpeepsApi: {
49
+ createPostAction: () => jest.fn(),
50
+ admin: { announcePostAction: () => jest.fn() },
51
+ joinGroupAction: () => jest.fn(),
52
+ useServerInfo: () => ({ data: { publicContent: true } }),
53
+ },
54
+ }),
55
+ }));
56
+
57
+ // --- common: the jest config pins the root import to contentLength.ts, which
58
+ // lacks these runtime helpers, so the page's named imports resolve here. --
59
+ jest.mock('@openpeepshq/common', () => ({
60
+ POLL_DEFAULT_EXPIRY_MS: 30 * 24 * 60 * 60 * 1000,
61
+ canAnnouncePosts: () => false,
62
+ isCommunityWideVisibility: () => true,
63
+ pollOptionsWithinLimit: () => true,
64
+ canSubmitPostContent: () => true,
65
+ resolvePollOptionContents: (opts: string[]) => opts,
66
+ visibleTextLength: (c?: string) => (c ?? '').length,
67
+ }));
68
+
69
+ // --- navigation: types are type-only, but the stack barrel is stubbed ------
70
+ jest.mock('@react-navigation/native', () => ({}));
71
+ jest.mock('@react-navigation/native-stack', () => ({}));
72
+
73
+ // --- local react-native deps ----------------------------------------------
74
+ jest.mock('react-native-toast-message', () => {
75
+ const Toast = { show: jest.fn() };
76
+ return { __esModule: true, default: Toast };
77
+ });
78
+ jest.mock('@gorhom/bottom-sheet', () => ({
79
+ BottomSheetModal: () => null,
80
+ }));
81
+ jest.mock('react-native-keyboard-aware-scroll-view', () => ({
82
+ KeyboardAwareScrollView: ({ children }: { children?: ReactNode }) =>
83
+ React.createElement('View', null, children),
84
+ }));
85
+
86
+ // --- react-hook-form: inert form, capturing reset() calls -----------------
87
+ let formResetCalls: unknown[][] = [];
88
+ jest.mock('react-hook-form', () => ({
89
+ useForm: () => ({
90
+ reset: (v?: unknown) => {
91
+ formResetCalls.push([v]);
92
+ },
93
+ }),
94
+ }));
95
+
96
+ // --- media permissions: always allowed (picker paths are inert) -----------
97
+ jest.mock('../../lib/media-permissions', () => ({
98
+ checkMediaPermissions: () => Promise.resolve(true),
99
+ }));
100
+
101
+ // --- layout + themed view: render inert ------------------------------------
102
+ jest.mock('../../components/layout', () => ({
103
+ HeaderActionButton: () => null,
104
+ useSetPageHeader: jest.fn(),
105
+ }));
106
+ jest.mock('../../components/ui/themed-view', () => ({
107
+ ThemedView: ({ children }: { children?: ReactNode }) =>
108
+ React.createElement('View', null, children),
109
+ }));
110
+
111
+ // --- picker sheets + article form: render inert ----------------------------
112
+ jest.mock('../../components/custom/index', () => ({
113
+ ImagePickerSheet: () => null,
114
+ AudioPickerSheet: () => null,
115
+ DocumentPickerSheet: () => null,
116
+ }));
117
+ jest.mock('../../components/post/index', () => ({
118
+ ArticleForm: () => null,
119
+ }));
120
+
121
+ // --- composer children: PostForm inert, PostTypeSwitcher forwards onSelect -
122
+ let switcherOnSelect: ((type: 'note' | 'question') => void) | undefined;
123
+ jest.mock('../../components/post/post-form/PostForm', () => ({
124
+ PostForm: () => null,
125
+ }));
126
+ jest.mock('../../components/post/post-form/PostTypeSwitcher', () => ({
127
+ PostTypeSwitcher: (props: {
128
+ type: string;
129
+ onSelect: (type: 'note' | 'question') => void;
130
+ }) => {
131
+ switcherOnSelect = props.onSelect;
132
+ return React.createElement('View', null);
133
+ },
134
+ }));
135
+ jest.mock('../../components/post/post-form/Footer', () => ({
136
+ // Renders the `typeSwitcher` slot so PostTypeSwitcher mounts and captures its
137
+ // onSelect (New.tsx passes the switcher as a prop, not a child).
138
+ Footer: (props: { typeSwitcher?: ReactNode }) =>
139
+ React.createElement('View', null, props.typeSwitcher),
140
+ }));
141
+
142
+ import { useLocalPostStore } from '../../stores/useLocalPostStore';
143
+ import { NewPost } from './New';
144
+
145
+ const NOTE_DRAFT = {
146
+ type: 'note',
147
+ visibility: 'public' as const,
148
+ data: { type: 'note' as const, content: '[TEST] note text before poll' },
149
+ mentions: [],
150
+ };
151
+
152
+ const QUESTION_DRAFT = {
153
+ type: 'question',
154
+ visibility: 'public' as const,
155
+ data: {
156
+ type: 'question' as const,
157
+ content: '[TEST] poll question',
158
+ options: [
159
+ { type: 'note' as const, content: 'Option A' },
160
+ { type: 'note' as const, content: 'Option B' },
161
+ ],
162
+ expiresAt: '2026-12-31T18:00:00.000Z',
163
+ },
164
+ mentions: [],
165
+ };
166
+
167
+ function render(): ReactTestRenderer.ReactTestRenderer {
168
+ let tree!: ReactTestRenderer.ReactTestRenderer;
169
+ ReactTestRenderer.act(() => {
170
+ tree = ReactTestRenderer.create(
171
+ <NewPost route={{ params: {} }} navigation={{}} />
172
+ );
173
+ });
174
+ return tree;
175
+ }
176
+
177
+ function clickSwitchTo(type: 'note' | 'question'): void {
178
+ expect(switcherOnSelect).toBeDefined();
179
+ ReactTestRenderer.act(() => {
180
+ switcherOnSelect!(type);
181
+ });
182
+ }
183
+
184
+ beforeEach(() => {
185
+ (
186
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
187
+ ).IS_REACT_ACT_ENVIRONMENT = true;
188
+ useLocalPostStore.getState().resetPostData();
189
+ useLocalPostStore.setState({
190
+ postData: QUESTION_DRAFT,
191
+ replyData: {},
192
+ });
193
+ formResetCalls = [];
194
+ switcherOnSelect = undefined;
195
+ });
196
+
197
+ test('poll -> note persists a note draft carrying the questionDraft stash', () => {
198
+ render();
199
+ clickSwitchTo('note');
200
+
201
+ // The converted draft is written to the app-lifetime local post store — the
202
+ // remount-restore path the screen comments rely on.
203
+ const stored = useLocalPostStore.getState().postData;
204
+ expect(stored.data).toMatchObject({
205
+ type: 'note',
206
+ content: '[TEST] poll question',
207
+ });
208
+ // The stash carries the poll's structural fields so a later note -> poll
209
+ // restores them instead of rebuilding a blank poll.
210
+ expect(stored.questionDraft).toMatchObject({
211
+ options: [
212
+ { type: 'note', content: 'Option A' },
213
+ { type: 'note', content: 'Option B' },
214
+ ],
215
+ expiresAt: '2026-12-31T18:00:00.000Z',
216
+ });
217
+ // The form is reset to the same converted draft (the handler passes one
218
+ // object to both form.reset and setPostData).
219
+ expect(formResetCalls.length).toBeGreaterThan(0);
220
+ const formNote = formResetCalls
221
+ .map((c) => c[0])
222
+ .find((p) => (p as { data?: { type?: string } })?.data?.type === 'note');
223
+ expect(formNote).toBe(stored);
224
+ });
225
+
226
+ test('note -> poll converts the note into a poll and drops the questionDraft stash', () => {
227
+ useLocalPostStore.setState({
228
+ postData: NOTE_DRAFT,
229
+ replyData: {},
230
+ });
231
+ render();
232
+ clickSwitchTo('question');
233
+
234
+ const stored = useLocalPostStore.getState().postData;
235
+ expect(stored.data).toMatchObject({
236
+ type: 'question',
237
+ content: '[TEST] note text before poll',
238
+ options: [
239
+ { type: 'note', content: '' },
240
+ { type: 'note', content: '' },
241
+ ],
242
+ });
243
+ // A note -> poll conversion has no stash to carry, so no questionDraft.
244
+ expect(stored.questionDraft).toBeUndefined();
245
+ });
@@ -11,7 +11,12 @@ import {
11
11
  MainStackParamList,
12
12
  TabStackParamList,
13
13
  } from '../../components/navigation/types/index';
14
- import { useOpenpeeps } from '@openpeepshq/react';
14
+ import {
15
+ isSwitchablePostData,
16
+ toNote,
17
+ toQuestion,
18
+ useOpenpeeps,
19
+ } from '@openpeepshq/react';
15
20
  import {
16
21
  AudioPickerSheet,
17
22
  ImagePickerSheet,
@@ -40,7 +45,7 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view
40
45
  import { Footer } from '../../components/post/post-form/Footer';
41
46
  import { PostTypeSwitcher } from '../../components/post/post-form/PostTypeSwitcher';
42
47
  import { BottomSheetModal } from '@gorhom/bottom-sheet';
43
- import { hasProcessingAttachments, toNote, toQuestion } from '../../lib/post';
48
+ import { hasProcessingAttachments } from '../../lib/post';
44
49
  import { useForm } from 'react-hook-form';
45
50
 
46
51
  import { ArticleForm } from '../../components/post/index';
@@ -234,9 +239,20 @@ export const NewPost = ({ route, navigation }: PostProps) => {
234
239
  if (postData.data.type === next) {
235
240
  return;
236
241
  }
242
+ if (!isSwitchablePostData(postData)) {
243
+ return;
244
+ }
237
245
  const newPostData =
238
246
  next === 'question' ? toQuestion(postData) : toNote(postData);
239
247
  form.reset(newPostData);
248
+ // Persisting the converted draft to the (module-scoped, app-lifetime)
249
+ // local post store is what makes the carry-over survive a screen
250
+ // unmount/remount: a fresh `NewPost` mount re-seeds its form from
251
+ // `useLocalPostStore.getState().postData`, so the converted note body /
252
+ // poll question (and, for a poll, its stashed `questionDraft` fields)
253
+ // are restored on return. A full app restart clears the store, so a
254
+ // draft only survives within a running app — matching the web, whose
255
+ // draft stores are in-memory too.
240
256
  setPostData(newPostData);
241
257
  },
242
258
  [postData, form, setPostData]
@@ -5,7 +5,13 @@ import React, {
5
5
  useRef,
6
6
  useState,
7
7
  } from 'react';
8
- import { apiErrorMessage, useOpenpeeps } from '@openpeepshq/react';
8
+ import {
9
+ apiErrorMessage,
10
+ isSwitchablePostData,
11
+ toNote,
12
+ toQuestion,
13
+ useOpenpeeps,
14
+ } from '@openpeepshq/react';
9
15
  import {
10
16
  AudioPickerSheet,
11
17
  DocumentPickerSheet,
@@ -40,7 +46,7 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view
40
46
  import { Footer } from '../../components/post/post-form/Footer';
41
47
  import { PostTypeSwitcher } from '../../components/post/post-form/PostTypeSwitcher';
42
48
  import { useForm } from 'react-hook-form';
43
- import { hasProcessingAttachments, toNote, toQuestion } from '../../lib/post';
49
+ import { hasProcessingAttachments } from '../../lib/post';
44
50
  import { CompactReplyParent } from '../../components/post/CompactReplyParent';
45
51
 
46
52
  import { ReplyModal } from '../../components/post/index';
@@ -230,9 +236,18 @@ export const ReplyPost = ({ route, navigation }: PostProps) => {
230
236
  if (!postData || postData.data.type === next) {
231
237
  return;
232
238
  }
239
+ if (!isSwitchablePostData(postData)) {
240
+ return;
241
+ }
233
242
  const newPostData =
234
243
  next === 'question' ? toQuestion(postData) : toNote(postData);
235
244
  form.reset(newPostData);
245
+ // Persisting the converted draft to the (module-scoped, app-lifetime)
246
+ // `replyData[id]` store slot is what makes the carry-over survive the
247
+ // reply screen unmounting/remounting: a fresh `ReplyPost` mount
248
+ // re-seeds its form from `useLocalPostStore(...).replyData[id]`, so the
249
+ // converted note body / poll question (and, for a poll, its stashed
250
+ // `questionDraft` fields) are restored on return.
236
251
  setPostData(newPostData);
237
252
  },
238
253
  [postData, form, setPostData]
@@ -1,4 +1,9 @@
1
- import { PostCreationData, PostType, PostDataUnion } from '@openpeepshq/common';
1
+ import {
2
+ POLL_DEFAULT_EXPIRY_MS,
3
+ PostCreationData,
4
+ PostType,
5
+ PostDataUnion,
6
+ } from '@openpeepshq/common';
2
7
  import { create } from 'zustand';
3
8
 
4
9
  const defaultPostData = (type: PostType): PostDataUnion => {
@@ -8,9 +13,7 @@ const defaultPostData = (type: PostType): PostDataUnion => {
8
13
  type: 'question',
9
14
  content: '',
10
15
  options: [],
11
- expiresAt: new Date(
12
- Date.now() + 1000 * 60 * 60 * 24 * 30
13
- ).toISOString(),
16
+ expiresAt: new Date(Date.now() + POLL_DEFAULT_EXPIRY_MS).toISOString(),
14
17
  };
15
18
  case 'event':
16
19
  return {