@openpeepshq/rn-components 0.16.0 → 0.17.0

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.
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Regression test for the EditProfileForm discoverable checkbox lifecycle
3
+ * (issue #211 round-3 review S2).
4
+ *
5
+ * The opt-out checkbox is driven by react-hook-form state. `useForm`'s
6
+ * `defaultValues` are only applied at mount, so if the profile fetch completes
7
+ * after mount (the common navigation path: a cached stub renders first, then
8
+ * the real profile resolves), the form keeps the stale `discoverable` value
9
+ * unless the `useEffect` keyed on `profileData` calls `form.reset`. If that
10
+ * reset were removed, a previously opted-out member would see the checkbox
11
+ * re-checked and an unrelated edit could silently flip the opt-out back on.
12
+ *
13
+ * This pins the lifecycle end to end: the component seeds the form from the
14
+ * cached stub at mount, then, when the fresh profile (discoverable: false)
15
+ * resolves after mount, it must call `form.reset` with the fresh flag. The
16
+ * assertion fails if the flag goes stale — i.e. if the post-mount reset is
17
+ * removed or no longer carries the loaded `discoverable`.
18
+ *
19
+ * `react-hook-form` is mocked with a spy `useForm` so the assertions read the
20
+ * actual `defaultValues` (mount seed) and the `reset` calls (post-mount sync)
21
+ * the component makes, without rendering the full native form tree.
22
+ */
23
+
24
+ const React = require('react');
25
+ const ReactTestRenderer = require('react-test-renderer');
26
+
27
+ jest.mock('react-native', () => ({
28
+ View: (props: Record<string, unknown>) =>
29
+ React.createElement('View', props, props.children),
30
+ Pressable: (props: { children?: unknown }) =>
31
+ React.createElement('Pressable', props, props.children),
32
+ ActivityIndicator: () => null,
33
+ }));
34
+
35
+ jest.mock('react-i18next', () => ({
36
+ useTranslation: () => ({ t: (key: string) => key }),
37
+ }));
38
+
39
+ jest.mock('react-native-toast-message', () => ({
40
+ __esModule: true,
41
+ default: { show: jest.fn() },
42
+ }));
43
+
44
+ jest.mock('react-native-keyboard-aware-scroll-view', () => ({
45
+ KeyboardAwareScrollView: (props: { children?: unknown }) =>
46
+ React.createElement('KeyboardAwareScrollView', null, props.children),
47
+ }));
48
+
49
+ jest.mock('@gorhom/bottom-sheet', () => ({
50
+ BottomSheetModal: () => null,
51
+ }));
52
+
53
+ // `@openpeepshq/common` is normally mapped to a single module; the component
54
+ // pulls value exports (profileSchema, isForbiddenHandle, ...) that live in the
55
+ // real barrel, so stub the exact names used here.
56
+ jest.mock('@openpeepshq/common', () => ({
57
+ getTheme: () => ({ defaultProfileAvatar: undefined }),
58
+ HANDLE_RESERVED_MESSAGE: 'reserved',
59
+ isForbiddenHandle: () => false,
60
+ profileSchema: {},
61
+ }));
62
+
63
+ // Inert resolver so the form never runs zod validation.
64
+ jest.mock('@hookform/resolvers/zod', () => ({
65
+ zodResolver: () => async () => ({}),
66
+ }));
67
+
68
+ jest.mock('../../lib/media-url', () => ({
69
+ toAbsoluteMediaUrl: (url?: string) => url,
70
+ }));
71
+
72
+ jest.mock('../ui/themed-view', () => ({
73
+ ThemedView: (props: { children?: unknown }) =>
74
+ React.createElement('ThemedView', null, props.children),
75
+ }));
76
+
77
+ jest.mock('../ui/themed-text', () => ({
78
+ ThemedText: (props: { children?: unknown }) =>
79
+ React.createElement('ThemedText', null, props.children),
80
+ }));
81
+
82
+ jest.mock('../ui/avatar', () => ({
83
+ Avatar: (props: { children?: unknown }) =>
84
+ React.createElement('Avatar', null, props.children),
85
+ AvatarImage: () => null,
86
+ }));
87
+
88
+ jest.mock('../ui/button', () => ({
89
+ Button: (props: { onPress?: () => void; children?: unknown }) =>
90
+ React.createElement('button', { onPress: props.onPress }, props.children),
91
+ }));
92
+
93
+ jest.mock('../custom/index', () => ({
94
+ ImagePickerSheet: () => null,
95
+ }));
96
+
97
+ jest.mock('../custom/common/index', () => ({
98
+ CachedImage: () => null,
99
+ }));
100
+
101
+ jest.mock('../icons/index', () => ({
102
+ CameraIcon: () => null,
103
+ XIcon: () => null,
104
+ }));
105
+
106
+ // Spy form: every `useForm` call returns a fresh object whose `reset` is a
107
+ // jest.fn, so the test can read the component's actual `defaultValues` (the
108
+ // mount seed) and its `reset` calls (the post-mount sync that keeps the
109
+ // discoverable checkbox in step with a freshly loaded profile).
110
+ jest.mock('react-hook-form', () => ({
111
+ useForm: jest.fn(() => ({
112
+ control: undefined,
113
+ formState: {},
114
+ reset: jest.fn(),
115
+ getValues: (name?: string) => (name ? formValues[name] : formValues),
116
+ handleSubmit: async () => {},
117
+ })),
118
+ FormProvider: () => null,
119
+ Controller: () => null,
120
+ }));
121
+
122
+ jest.mock('../ui/form', () => ({
123
+ // Renders children so the submit Button (the only exposed trigger of
124
+ // `onSubmit`) is reachable in the submit-path test; the form fields stay
125
+ // inert.
126
+ Form: (props: { children?: unknown }) =>
127
+ React.createElement('Form', null, props.children),
128
+ FormField: () => null,
129
+ FormInput: () => null,
130
+ FormTextarea: () => null,
131
+ FormCheckbox: () => null,
132
+ }));
133
+
134
+ // Controllable profile so the test can resolve the fresh profile after mount.
135
+ const profileState = {
136
+ data: undefined as unknown,
137
+ isLoading: false,
138
+ };
139
+
140
+ // Controllable form values so the submit-path test exercises what the native
141
+ // app actually persists. `react-hook-form` is mocked, so the zod resolver
142
+ // never runs and `getValues` returns this verbatim: a dropped or mangled
143
+ // `discoverable` in `onSubmit` surfaces here, not at validation.
144
+ const formValues: Record<string, unknown> = {};
145
+
146
+ // Captures the `updateCurrentProfileAction()` instance the form calls, so the
147
+ // submit-path test asserts the exact persisted payload. Stable across renders
148
+ // — `useOpenpeeps` returns a stable api (context), and the form re-renders on
149
+ // `setIsSubmitting`, so a fresh action per render would let the re-render
150
+ // silently swap out the reference the test asserts on.
151
+ let updateAction: jest.Mock = jest.fn(async () => ({}));
152
+
153
+ // Captures every `queryClient.invalidateQueries` call from the save path so
154
+ // the round-6 S2 pin can assert the profile-list caches are dropped when
155
+ // `discoverable` is toggled (directory view `['profiles', { directory: 'true' }]`
156
+ // and pickers `['profiles']` via the `['profiles']` prefix).
157
+ const invalidateQueriesSpy = jest.fn(async () => {});
158
+
159
+ jest.mock('@openpeepshq/react', () => ({
160
+ useOpenpeeps: () => ({
161
+ openpeepsApi: {
162
+ useProfileByHandle: () => ({
163
+ data: profileState.data,
164
+ isLoading: profileState.isLoading,
165
+ refetch: jest.fn(async () => {}),
166
+ }),
167
+ useServerInfo: () => ({
168
+ data: { communityConfig: { settings: {}, profiles: {} } },
169
+ }),
170
+ updateCurrentProfileAction: () => updateAction,
171
+ },
172
+ queryClient: { invalidateQueries: invalidateQueriesSpy },
173
+ }),
174
+ useServerInfo: () => ({
175
+ communityConfig: { settings: {}, profiles: {} },
176
+ }),
177
+ }));
178
+
179
+ import * as reactHookForm from 'react-hook-form';
180
+ import { EditProfileForm } from './EditProfileForm';
181
+
182
+ const useFormMock = reactHookForm.useForm as jest.Mock;
183
+
184
+ beforeEach(() => {
185
+ (
186
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
187
+ ).IS_REACT_ACT_ENVIRONMENT = true;
188
+ useFormMock.mockClear();
189
+ Object.keys(formValues).forEach((key) => delete formValues[key]);
190
+ formValues.displayName = 'Me';
191
+ formValues.handle = 'me';
192
+ formValues.fields = [];
193
+ updateAction.mockReset();
194
+ updateAction.mockResolvedValue({});
195
+ invalidateQueriesSpy.mockClear();
196
+ });
197
+
198
+ const baseProfile = (discoverable: boolean | undefined) => ({
199
+ id: 'me',
200
+ handle: 'me',
201
+ displayName: 'Me',
202
+ type: 'local',
203
+ fields: [],
204
+ ...(discoverable === undefined ? {} : { discoverable }),
205
+ });
206
+
207
+ describe('EditProfileForm discoverable checkbox lifecycle (issue #211 S2)', () => {
208
+ it('resets the form to the freshly loaded discoverable flag, not the cached stub', () => {
209
+ // Cached stub: member is listed (discoverable present/truthy).
210
+ profileState.data = baseProfile(true);
211
+ profileState.isLoading = false;
212
+
213
+ let tree: ReturnType<typeof ReactTestRenderer.create>;
214
+ ReactTestRenderer.act(() => {
215
+ tree = ReactTestRenderer.create(
216
+ React.createElement(EditProfileForm, { handle: 'me' })
217
+ );
218
+ });
219
+
220
+ // Mount seed: the form is initialised from the cached stub's discoverable.
221
+ const mountCall = useFormMock.mock.calls[0][0];
222
+ expect(mountCall.defaultValues.discoverable).toBe(true);
223
+
224
+ // Fresh profile resolves after mount with the member opted out.
225
+ ReactTestRenderer.act(() => {
226
+ profileState.data = baseProfile(false);
227
+ (tree as { update: (el: React.ReactElement) => void }).update(
228
+ React.createElement(EditProfileForm, { handle: 'me' })
229
+ );
230
+ });
231
+
232
+ // The effect keyed on profileData must call form.reset with the fresh
233
+ // flag. A stale form (reset removed or not carrying discoverable) would
234
+ // never hand the fresh `false` to the form, and this would fail.
235
+ const resetCalls = useFormMock.mock.results.map(
236
+ (r) => r.value.reset as jest.Mock
237
+ );
238
+ const handedFreshFlag = resetCalls.some((spy) =>
239
+ spy.mock.calls.some((call) => call[0]?.discoverable === false)
240
+ );
241
+ expect(handedFreshFlag).toBe(true);
242
+ });
243
+ });
244
+
245
+ describe('EditProfileForm discoverable checkbox submit path (issue #211 S2)', () => {
246
+ const mountForm = () => {
247
+ profileState.data = baseProfile(false);
248
+ profileState.isLoading = false;
249
+ let tree: ReturnType<typeof ReactTestRenderer.create>;
250
+ ReactTestRenderer.act(() => {
251
+ tree = ReactTestRenderer.create(
252
+ React.createElement(EditProfileForm, { handle: 'me' })
253
+ );
254
+ });
255
+ return tree;
256
+ };
257
+
258
+ const pressSubmit = async (
259
+ tree: ReturnType<typeof ReactTestRenderer.create>
260
+ ) => {
261
+ const button = tree.root.find((node) => node.type === 'button') as {
262
+ props: { onPress: () => void };
263
+ };
264
+ await ReactTestRenderer.act(async () => {
265
+ button.props.onPress();
266
+ });
267
+ };
268
+
269
+ it('persists discoverable: false when an opted-out member saves', async () => {
270
+ const tree = mountForm();
271
+ formValues.discoverable = false;
272
+
273
+ await pressSubmit(tree);
274
+
275
+ expect(updateAction).toHaveBeenCalledTimes(1);
276
+ // The payload the native app persists must carry the flag verbatim —
277
+ // an absent `discoverable` (or one mangled to truthy) would leave the
278
+ // opt-out silently reverted, which this assertion catches.
279
+ expect(updateAction!.mock.calls[0]![0]).toMatchObject({
280
+ discoverable: false,
281
+ });
282
+ });
283
+
284
+ it('persists discoverable: true when a member re-joins the directory', async () => {
285
+ const tree = mountForm();
286
+ formValues.discoverable = true;
287
+
288
+ await pressSubmit(tree);
289
+
290
+ expect(updateAction).toHaveBeenCalledTimes(1);
291
+ expect(updateAction!.mock.calls[0]![0]).toMatchObject({
292
+ discoverable: true,
293
+ });
294
+ });
295
+
296
+ it('drops the profile-list caches on save so the directory refetches (issue #211 round-6 S2)', async () => {
297
+ const tree = mountForm();
298
+ formValues.discoverable = false;
299
+
300
+ await pressSubmit(tree);
301
+
302
+ // Toggling `discoverable` changes directory membership. Without the
303
+ // `['profiles']` invalidation the RN Members tab (and the profile
304
+ // pickers) would keep showing the member until their next refetch — the
305
+ // screen stays mounted in the tab navigator and the app has no query
306
+ // focusManager wiring. The `['profiles']` prefix matches both the
307
+ // directory query (`['profiles', { directory: 'true' }]`) and the
308
+ // pickers' plain `['profiles']` key. The exact call shape is pinned, not
309
+ // just "some profiles-ish key": the pre-existing `['profile', handle]`
310
+ // call does not satisfy it, so a regression that drops only this
311
+ // invalidation still fails the test.
312
+ expect(invalidateQueriesSpy.mock.calls).toContainEqual([
313
+ { queryKey: ['profiles'] },
314
+ ]);
315
+ });
316
+ });
@@ -17,7 +17,13 @@ import { zodResolver } from '@hookform/resolvers/zod';
17
17
  import { ActivityIndicator, Pressable, View } from 'react-native';
18
18
  import { Avatar, AvatarImage } from '../ui/avatar';
19
19
  import { CachedImage } from '../custom/common/index';
20
- import { Form, FormField, FormInput, FormTextarea } from '../ui/form';
20
+ import {
21
+ Form,
22
+ FormCheckbox,
23
+ FormField,
24
+ FormInput,
25
+ FormTextarea,
26
+ } from '../ui/form';
21
27
  import Toast from 'react-native-toast-message';
22
28
  import { ImagePickerSheet } from '../custom/index';
23
29
  import { CameraIcon, XIcon } from '../icons/index';
@@ -78,6 +84,7 @@ export const EditProfileForm: React.FC<EditProfileFormProps> = ({ handle }) => {
78
84
  displayName: profileData.displayName || '',
79
85
  bio: profileData.bio || '',
80
86
  location: (profileData as ProfileData)?.location || { text: '' },
87
+ discoverable: profileData.discoverable,
81
88
  fields: customFields || [],
82
89
  handle,
83
90
  });
@@ -117,8 +124,7 @@ export const EditProfileForm: React.FC<EditProfileFormProps> = ({ handle }) => {
117
124
  values.fields = values.fields?.filter((field) => !!field.value);
118
125
 
119
126
  updateProfileDetails(values)
120
- .then(async (response) => {
121
- console.log('response', response);
127
+ .then(async () => {
122
128
  Toast.show({
123
129
  type: 'success',
124
130
  text2: t('profile.edit.success'),
@@ -130,6 +136,14 @@ export const EditProfileForm: React.FC<EditProfileFormProps> = ({ handle }) => {
130
136
  await queryClient.invalidateQueries({
131
137
  queryKey: ['profile', handle],
132
138
  });
139
+ // Toggling `discoverable` changes directory membership, so drop the
140
+ // cached profile lists too (the directory view is keyed
141
+ // `['profiles', { directory: 'true' }]` and the pickers `['profiles']`);
142
+ // the `['profiles']` prefix matches both. Without this the RN Members
143
+ // tab would keep showing the member until its next refetch.
144
+ await queryClient.invalidateQueries({
145
+ queryKey: ['profiles'],
146
+ });
133
147
  await refetch();
134
148
  })
135
149
  .catch((err) => {
@@ -152,7 +166,6 @@ export const EditProfileForm: React.FC<EditProfileFormProps> = ({ handle }) => {
152
166
  };
153
167
  const handleSubmit = async () => {
154
168
  const values = form.getValues();
155
- console.log('values', values);
156
169
  await onSubmit(values);
157
170
  };
158
171
 
@@ -350,6 +363,22 @@ export const EditProfileForm: React.FC<EditProfileFormProps> = ({ handle }) => {
350
363
  )}
351
364
  />
352
365
  </View>
366
+ <View className="relative w-full">
367
+ <FormField
368
+ control={form.control}
369
+ name="discoverable"
370
+ render={({ field }) => (
371
+ <FormCheckbox
372
+ {...field}
373
+ checked={field.value !== false}
374
+ onCheckedChange={field.onChange}
375
+ custom={false}
376
+ label={t('profile.form.discoverable')}
377
+ description={t('profile.form.discoverableHint')}
378
+ />
379
+ )}
380
+ />
381
+ </View>
353
382
  {serverInfo?.communityConfig.profiles?.additionalFields?.map(
354
383
  (field, index) => {
355
384
  return (