@openpeepshq/rn-components 0.17.0 → 0.19.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,247 @@
1
+ /**
2
+ * RN parity for the community-jam "notify everyone" opt-in (issue #1621): the
3
+ * native event form must render the opt-in checkbox only when the profile can
4
+ * announce posts (`core-posts-announce`) AND the post visibility is
5
+ * community-wide, mirroring
6
+ * platform/react/src/components/post/post-form/EventTypeSwitcher.tsx.
7
+ *
8
+ * react-native, the UI primitives and the shared `@openpeepshq/react` hooks are
9
+ * stubbed; the two gate predicates come from `@openpeepshq/common` with the
10
+ * exact semantics of `canAnnouncePosts` / `isCommunityWideVisibility`, fed by
11
+ * `state`, so the test pins the gate without depending on the workspace
12
+ * symlink target carrying the role surface.
13
+ *
14
+ * Unlike counting `Checkbox` renders, the tests identify each checkbox by the
15
+ * handler its `onCheckedChange` is wired to. The `@openpeepshq/react` mock
16
+ * mirrors the real `useEventTypeSwitcher` contract: `setWaitingRoom` /
17
+ * `setNotifyEveryone` each spread `event` and write the matching `jam` field,
18
+ * then call the component's `onChange`. So the notify checkbox is recognized by
19
+ * `onCheckedChange === setNotifyEveryone` (not by a render count that the
20
+ * always-present waiting-room checkbox would inflate), and firing it is asserted
21
+ * to drive `onChange` with `jam.notifyEveryone: true`.
22
+ */
23
+
24
+ const React = require('react');
25
+ const ReactTestRenderer = require('react-test-renderer');
26
+
27
+ (
28
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
29
+ ).IS_REACT_ACT_ENVIRONMENT = true;
30
+
31
+ // Shared `useAuthData` mock surface (same module the web parity test drives
32
+ // against `IdentityContext`), so the profile the tree sees is identical on
33
+ // both platforms.
34
+ const {
35
+ authDataState,
36
+ makeAuthDataValue,
37
+ } = require('../../../../../react/src/test/support/mockAuth');
38
+
39
+ type CheckboxProps = {
40
+ checked?: boolean;
41
+ disabled?: boolean;
42
+ onCheckedChange?: (value: boolean) => void;
43
+ };
44
+
45
+ // Every Checkbox the tree renders, in order, with the props it was handed.
46
+ let checkboxes: CheckboxProps[] = [];
47
+ // Handler identities handed to the component this render, used to tell the
48
+ // notify checkbox apart from the always-present waiting-room checkbox.
49
+ let setWaitingRoom: ((value: boolean) => void) | undefined;
50
+ let setNotifyEveryone: ((value: boolean) => void) | undefined;
51
+
52
+ jest.mock('react-native', () => ({
53
+ View: (props: { children?: unknown }) =>
54
+ React.createElement('View', null, props.children),
55
+ Pressable: (props: { children?: unknown }) =>
56
+ React.createElement('Pressable', null, props.children),
57
+ }));
58
+
59
+ jest.mock('react-i18next', () => ({
60
+ useTranslation: () => ({ t: (key: string) => key }),
61
+ }));
62
+
63
+ // Mirrored from platform/common/src/lib — the package entry the test would
64
+ // otherwise load through the workspace symlink may not carry the role surface.
65
+ jest.mock('@openpeepshq/common', () => ({
66
+ canAnnouncePosts: (roles: { capabilities?: { add?: string[] } }[] = []) =>
67
+ roles.some((r) =>
68
+ (r.capabilities?.add ?? []).includes('core-posts-announce')
69
+ ),
70
+ isCommunityWideVisibility: (visibility?: string) =>
71
+ visibility === 'public' || visibility === 'local',
72
+ }));
73
+
74
+ jest.mock('@openpeepshq/react', () => ({
75
+ useAuthData: makeAuthDataValue,
76
+ useEventTypeSwitcher: (args: {
77
+ event: { jam?: Record<string, unknown> };
78
+ onChange: (event: unknown) => void;
79
+ }) => {
80
+ // Mirror the real hook (platform/react useEventTypeSwitcher): both setters
81
+ // spread the current event, write their jam field, and call onChange.
82
+ setWaitingRoom = (value: boolean) =>
83
+ args.onChange({
84
+ ...args.event,
85
+ jam: { ...args.event.jam, waitingRoom: value },
86
+ });
87
+ setNotifyEveryone = (value: boolean) =>
88
+ args.onChange({
89
+ ...args.event,
90
+ jam: { ...args.event.jam, notifyEveryone: value },
91
+ });
92
+ return {
93
+ eventFormat: 'jam',
94
+ formats: [{ value: 'jam', label: 'events.form.jamFormat' }],
95
+ livekitEnabled: true,
96
+ switchFormat: () => undefined,
97
+ moderatorProfiles: [],
98
+ setModerators: () => undefined,
99
+ setWaitingRoom,
100
+ setNotifyEveryone,
101
+ setUrl: () => undefined,
102
+ setPhysicalLocation: () => undefined,
103
+ };
104
+ },
105
+ useLocationSearch: () => ({
106
+ text: '',
107
+ setText: () => undefined,
108
+ suggestions: [],
109
+ clearSuggestions: () => undefined,
110
+ search: () => undefined,
111
+ }),
112
+ }));
113
+
114
+ jest.mock('../../ui/checkbox', () => ({
115
+ Checkbox: (props: CheckboxProps) => {
116
+ checkboxes.push(props);
117
+ return React.createElement('Checkbox', props);
118
+ },
119
+ }));
120
+ jest.mock('../../ui/input', () => ({
121
+ Input: () => React.createElement('Input'),
122
+ }));
123
+ jest.mock('../../ui/label', () => ({
124
+ Label: ({ children }: { children?: unknown }) =>
125
+ React.createElement('Label', null, children),
126
+ }));
127
+ jest.mock('../../ui/radio-group', () => ({
128
+ RadioGroup: ({ children }: { children?: unknown }) =>
129
+ React.createElement('RadioGroup', null, children),
130
+ RadioGroupItem: (props: Record<string, unknown>) =>
131
+ React.createElement('RadioGroupItem', props),
132
+ }));
133
+ jest.mock('../../ui/themed-text', () => ({
134
+ ThemedText: ({ children }: { children?: unknown }) =>
135
+ React.createElement('ThemedText', null, children),
136
+ }));
137
+ jest.mock('../../../lib/constants', () => ({ BASE_URL: 'http://localhost' }));
138
+ jest.mock('../../profile/ProfilesInput', () => ({
139
+ ProfilesInput: () => React.createElement('ProfilesInput'),
140
+ }));
141
+
142
+ const { EventTypeSwitcher } = require('./EventTypeSwitcher');
143
+
144
+ const event = { type: 'event', name: 'Standup', jam: {} };
145
+
146
+ // Renders the tree (driving the gate) and returns every checkbox it produced,
147
+ // so callers can pick the one wired to the setter they care about.
148
+ const render = (visibility?: string, onChange?: (event: unknown) => void) => {
149
+ checkboxes = [];
150
+ setWaitingRoom = undefined;
151
+ setNotifyEveryone = undefined;
152
+ ReactTestRenderer.act(() => {
153
+ ReactTestRenderer.create(
154
+ React.createElement(EventTypeSwitcher, {
155
+ event,
156
+ onChange: onChange ?? (() => undefined),
157
+ visibility,
158
+ })
159
+ );
160
+ });
161
+ return checkboxes;
162
+ };
163
+
164
+ // True only when the tree renders exactly one checkbox and it is the
165
+ // waiting-room one — i.e. the notify opt-in is absent (the `>= 2` count the
166
+ // old render-count assertions relied on would be satisfied by a future third
167
+ // toggle; identity is not).
168
+ const waitingRoomOnly = (boxes: CheckboxProps[]) =>
169
+ boxes.length === 1 && boxes[0].onCheckedChange === setWaitingRoom;
170
+
171
+ const notifyCheckbox = (boxes: CheckboxProps[]) =>
172
+ boxes.find((b) => b.onCheckedChange === setNotifyEveryone);
173
+
174
+ describe('RN EventTypeSwitcher community jam broadcast opt-in', () => {
175
+ beforeEach(() => {
176
+ authDataState.roles = [];
177
+ });
178
+
179
+ it('shows the opt-in for a public jam when the role can announce posts', () => {
180
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
181
+ const boxes = render('public');
182
+ expect(boxes).toHaveLength(2);
183
+ expect(notifyCheckbox(boxes)).toBeDefined();
184
+ });
185
+
186
+ it('shows the opt-in for a local jam with the announce role', () => {
187
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
188
+ const boxes = render('local');
189
+ expect(boxes).toHaveLength(2);
190
+ expect(notifyCheckbox(boxes)).toBeDefined();
191
+ });
192
+
193
+ it('keeps the waiting-room checkbox as the only checkbox for a group jam', () => {
194
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
195
+ expect(waitingRoomOnly(render('group'))).toBe(true);
196
+ });
197
+
198
+ it('keeps the waiting-room checkbox as the only checkbox for a direct jam', () => {
199
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
200
+ expect(waitingRoomOnly(render('direct'))).toBe(true);
201
+ });
202
+
203
+ it('keeps the waiting-room checkbox as the only checkbox without the announce role', () => {
204
+ authDataState.roles = [{ capabilities: { add: ['core-posts-create'] } }];
205
+ expect(waitingRoomOnly(render('public'))).toBe(true);
206
+ });
207
+
208
+ it('keeps the waiting-room checkbox as the only checkbox when no visibility is supplied', () => {
209
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
210
+ expect(waitingRoomOnly(render(undefined))).toBe(true);
211
+ });
212
+
213
+ it('drives onChange with jam.notifyEveryone: true when the opt-in is toggled on', () => {
214
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
215
+ const onChange = jest.fn();
216
+ const boxes = render('public', onChange);
217
+ const notify = notifyCheckbox(boxes);
218
+ expect(notify).toBeDefined();
219
+ expect(notify!.checked).toBe(false);
220
+
221
+ notify!.onCheckedChange!(true);
222
+
223
+ expect(onChange).toHaveBeenCalledTimes(1);
224
+ expect(onChange).toHaveBeenCalledWith(
225
+ expect.objectContaining({
226
+ jam: expect.objectContaining({ notifyEveryone: true }),
227
+ })
228
+ );
229
+ });
230
+
231
+ it('drives onChange with jam.waitingRoom: true when the waiting-room toggle is toggled', () => {
232
+ authDataState.roles = [{ capabilities: { add: ['core-posts-announce'] } }];
233
+ const onChange = jest.fn();
234
+ const boxes = render('public', onChange);
235
+ const waitingRoom = boxes.find((b) => b.onCheckedChange === setWaitingRoom);
236
+ expect(waitingRoom).toBeDefined();
237
+
238
+ waitingRoom!.onCheckedChange!(true);
239
+
240
+ expect(onChange).toHaveBeenCalledTimes(1);
241
+ expect(onChange).toHaveBeenCalledWith(
242
+ expect.objectContaining({
243
+ jam: expect.objectContaining({ waitingRoom: true }),
244
+ })
245
+ );
246
+ });
247
+ });
@@ -2,7 +2,15 @@ import React from 'react';
2
2
  import { Pressable, View } from 'react-native';
3
3
  import { useTranslation } from 'react-i18next';
4
4
  import type { Event, Location } from '@openpeepshq/common';
5
- import { useEventTypeSwitcher, useLocationSearch } from '@openpeepshq/react';
5
+ import {
6
+ canAnnouncePosts,
7
+ isCommunityWideVisibility,
8
+ } from '@openpeepshq/common';
9
+ import {
10
+ useAuthData,
11
+ useEventTypeSwitcher,
12
+ useLocationSearch,
13
+ } from '@openpeepshq/react';
6
14
  import { Checkbox } from '../../ui/checkbox';
7
15
  import { Input } from '../../ui/input';
8
16
  import { Label } from '../../ui/label';
@@ -17,6 +25,8 @@ export interface EventTypeSwitcherProps {
17
25
  event: Event;
18
26
  isEdit?: boolean;
19
27
  onChange: (event: Event) => void;
28
+ /** Post visibility; gates the community-wide "notify everyone" opt-in. */
29
+ visibility?: string;
20
30
  }
21
31
 
22
32
  const SimpleLocationInput = ({
@@ -67,8 +77,13 @@ export const EventTypeSwitcher = ({
67
77
  event,
68
78
  isEdit = false,
69
79
  onChange,
80
+ visibility,
70
81
  }: EventTypeSwitcherProps) => {
71
82
  const { t } = useTranslation();
83
+ const authData = useAuthData();
84
+ const canNotify =
85
+ canAnnouncePosts(authData.profile?.roles) &&
86
+ isCommunityWideVisibility(visibility);
72
87
  const {
73
88
  eventFormat,
74
89
  formats,
@@ -77,6 +92,7 @@ export const EventTypeSwitcher = ({
77
92
  moderatorProfiles,
78
93
  setModerators,
79
94
  setWaitingRoom,
95
+ setNotifyEveryone,
80
96
  setUrl,
81
97
  setPhysicalLocation,
82
98
  } = useEventTypeSwitcher({ event, isEdit, onChange, origin: BASE_URL ?? '' });
@@ -157,6 +173,25 @@ export const EventTypeSwitcher = ({
157
173
  {t('events.form.jamWaitingRoom')}
158
174
  </ThemedText>
159
175
  </View>
176
+ {canNotify ? (
177
+ <View className="gap-1">
178
+ <View className="flex-row items-start gap-2">
179
+ <View className="pt-0.5">
180
+ <Checkbox
181
+ checked={event.jam?.notifyEveryone ?? false}
182
+ disabled={!livekitEnabled}
183
+ onCheckedChange={setNotifyEveryone}
184
+ />
185
+ </View>
186
+ <ThemedText className="text-sm">
187
+ {t('events.form.jamNotifyEveryone')}
188
+ </ThemedText>
189
+ </View>
190
+ <ThemedText className="text-xs text-muted-foreground pl-6">
191
+ {t('events.form.jamNotifyEveryoneDescription')}
192
+ </ThemedText>
193
+ </View>
194
+ ) : null}
160
195
  </>
161
196
  ) : null}
162
197
  </View>
@@ -15,11 +15,43 @@
15
15
  const React = require('react');
16
16
  const ReactTestRenderer = require('react-test-renderer');
17
17
 
18
+ // Mocked element types, shared with the jest.mock factories below so tests can
19
+ // assert tree order by reference instead of by string name. The tile's style
20
+ // (backgroundColor / fontSize) is forwarded so the underlay's actual styling
21
+ // can be pinned, not just its presence and tree position.
22
+ const MockView = (props: {
23
+ children?: unknown;
24
+ className?: string;
25
+ style?: unknown;
26
+ }) =>
27
+ React.createElement(
28
+ 'View',
29
+ { className: props.className, style: props.style },
30
+ props.children
31
+ );
32
+ const MockText = (props: {
33
+ children?: unknown;
34
+ className?: string;
35
+ style?: unknown;
36
+ }) =>
37
+ React.createElement(
38
+ 'Text',
39
+ { className: props.className, style: props.style },
40
+ props.children
41
+ );
42
+ const MockAvatar = (props: { children?: unknown; className?: string }) =>
43
+ React.createElement('Avatar', { className: props.className }, props.children);
44
+ const MockAvatarImage = (props: { source?: unknown; className?: string }) =>
45
+ React.createElement('AvatarImage', { source: props.source });
46
+ const MockSvgImage = (props: { uri?: string; className?: string }) =>
47
+ React.createElement('SvgImage', {
48
+ uri: props.uri,
49
+ className: props.className,
50
+ });
51
+
18
52
  jest.mock('react-native', () => ({
19
- View: (props: { children?: unknown; className?: string }) =>
20
- React.createElement('View', { className: props.className }, props.children),
21
- Text: (props: { children?: unknown; className?: string }) =>
22
- React.createElement('Text', { className: props.className }, props.children),
53
+ View: MockView,
54
+ Text: MockText,
23
55
  }));
24
56
 
25
57
  jest.mock('react-i18next', () => ({
@@ -47,23 +79,13 @@ jest.mock('../../theme/OpenPeepsThemeProvider', () => ({
47
79
  }));
48
80
 
49
81
  jest.mock('../ui/avatar', () => ({
50
- Avatar: (props: { children?: unknown; className?: string }) =>
51
- React.createElement(
52
- 'Avatar',
53
- { className: props.className },
54
- props.children
55
- ),
82
+ Avatar: MockAvatar,
56
83
  AvatarFallback: () => null,
57
- AvatarImage: (props: { source?: unknown; className?: string }) =>
58
- React.createElement('AvatarImage', { source: props.source }),
84
+ AvatarImage: MockAvatarImage,
59
85
  }));
60
86
 
61
87
  jest.mock('../ui/svg-image', () => ({
62
- SvgImage: (props: { uri?: string; className?: string }) =>
63
- React.createElement('SvgImage', {
64
- uri: props.uri,
65
- className: props.className,
66
- }),
88
+ SvgImage: MockSvgImage,
67
89
  }));
68
90
 
69
91
  jest.mock('../icons/index', () => ({
@@ -144,4 +166,67 @@ describe('ProfileAvatar SVG path selection (issue #1666 round-2 plan step 2)', (
144
166
  .find((child) => typeof child === 'string');
145
167
  expect(initials).toBe('AL');
146
168
  });
169
+
170
+ it('renders the initials tile under the SVG image (issue #1666 round-3)', () => {
171
+ // Both children must render simultaneously, with the tile first in tree
172
+ // order so a loaded SvgImage paints over it (a re-order, or a condition
173
+ // that hides the image, must fail this test).
174
+ const tree = renderAvatar({
175
+ ...baseProfile,
176
+ avatar: 'https://cdn.example/avatars/ada.svg',
177
+ });
178
+ const avatar = tree.root.findByType('Avatar');
179
+ const initials = tree.root
180
+ .findAllByType('Text')
181
+ .map((node: { props: { children?: unknown } }) => node.props.children)
182
+ .find((child) => typeof child === 'string');
183
+ expect(initials).toBe('AL');
184
+ expect(avatar.findAllByType(MockSvgImage)).toHaveLength(1);
185
+ const childTypes = avatar.children.map(
186
+ (child: { type?: unknown }) => child.type
187
+ );
188
+ expect(childTypes[0]).toBe(MockView);
189
+ expect(childTypes[childTypes.length - 1]).toBe(MockSvgImage);
190
+ });
191
+
192
+ it('renders the initials tile under the raster image (issue #1666 round-3)', () => {
193
+ // Both children must render simultaneously, with the tile first in tree
194
+ // order so a loaded AvatarImage paints over it (a re-order, or a
195
+ // condition that hides the image, must fail this test).
196
+ const tree = renderAvatar({
197
+ ...baseProfile,
198
+ avatar: 'https://cdn.example/avatars/ada.png',
199
+ });
200
+ const avatar = tree.root.findByType('Avatar');
201
+ const initials = tree.root
202
+ .findAllByType('Text')
203
+ .map((node: { props: { children?: unknown } }) => node.props.children)
204
+ .find((child) => typeof child === 'string');
205
+ expect(initials).toBe('AL');
206
+ expect(avatar.findAllByType(MockAvatarImage)).toHaveLength(1);
207
+ const childTypes = avatar.children.map(
208
+ (child: { type?: unknown }) => child.type
209
+ );
210
+ expect(childTypes[0]).toBe(MockView);
211
+ expect(childTypes[childTypes.length - 1]).toBe(MockAvatarImage);
212
+ });
213
+
214
+ it('pins the underlay style: tile background from initialsBackground and size-derived fontSize (issue #1666 round-20 #1)', () => {
215
+ // The loading-gap symptom is invisible-if-unstyled: a refactor that drops
216
+ // the tile's style must fail here. size-10 → 40dp → fontSize 15, and the
217
+ // background is the real initialsBackground output for the mocked hue.
218
+ const tree = renderAvatar({
219
+ ...baseProfile,
220
+ avatar: 'https://cdn.example/avatars/ada.png',
221
+ });
222
+ const tile = tree.root
223
+ .findAllByType(MockView)
224
+ .find((node) => typeof node.props.style?.backgroundColor === 'string');
225
+ expect(tile.props.style.backgroundColor).toBe('rgb(20, 20, 20)');
226
+ // The tile's single child is the initials Text (not an array).
227
+ const text = Array.isArray(tile.props.children)
228
+ ? tile.props.children[0]
229
+ : tile.props.children;
230
+ expect(text.props.style.fontSize).toBe(15);
231
+ });
147
232
  });
@@ -55,8 +55,27 @@ export const ProfileAvatar = ({
55
55
  !deleted && profile?.avatar ? { uri: svgCoverSrc(profile.avatar) } : null;
56
56
 
57
57
  const hue = hueFromHandle(profile?.handle ?? '');
58
- const backgroundColor =
59
- !deleted && !avatarSource ? initialsBackground(hue, isDark) : undefined;
58
+ const initialsBg = !deleted ? initialsBackground(hue, isDark) : undefined;
59
+
60
+ // The initials tile is the underlay behind both image branches (absolutely
61
+ // positioned to fill the avatar box): while a remote/SVG avatar is still
62
+ // downloading — or permanently, when the media cache cannot produce the
63
+ // file — it is the visible content, and it doubles as the standalone
64
+ // content for no-avatar profiles. Either way every row carries sized,
65
+ // centered content (issue #1666).
66
+ const initialsTile = (
67
+ <View
68
+ className={cn(
69
+ 'absolute inset-0 flex items-center justify-center',
70
+ roundedClass
71
+ )}
72
+ style={{ backgroundColor: initialsBg }}
73
+ >
74
+ <Text className="text-foreground font-medium" style={{ fontSize }}>
75
+ {getInitials(profile?.displayName, profile?.handle)}
76
+ </Text>
77
+ </View>
78
+ );
60
79
 
61
80
  const rootClassName = cn(
62
81
  'border border-muted-foreground overflow-hidden',
@@ -71,27 +90,26 @@ export const ProfileAvatar = ({
71
90
  className={rootClassName}
72
91
  style={{ width: px, height: px }}
73
92
  >
74
- <View
75
- className={cn(
76
- 'flex h-full w-full items-center justify-center',
77
- roundedClass
78
- )}
79
- style={{ backgroundColor }}
80
- >
81
- {deleted ? (
93
+ {deleted ? (
94
+ <View
95
+ className={cn(
96
+ 'flex h-full w-full items-center justify-center',
97
+ roundedClass
98
+ )}
99
+ >
82
100
  <UserXIcon size={iconSize} className="text-muted-foreground" />
83
- ) : (
84
- <Text className="text-foreground font-medium" style={{ fontSize }}>
85
- {getInitials(profile?.displayName, profile?.handle)}
86
- </Text>
87
- )}
88
- </View>
101
+ </View>
102
+ ) : (
103
+ initialsTile
104
+ )}
89
105
  </Avatar>
90
106
  );
91
107
  }
92
108
 
93
- // RN Image cannot decode SVG: render via SvgImage, which ignores the
94
- // #svgView fragment and applies cover natively via preserveAspectRatio.
109
+ // The image branches render the initials tile underneath the image: while
110
+ // the media cache is still downloading (or an SVG has not reached the
111
+ // decode-ready state) the avatar shows the same tile as no-avatar
112
+ // profiles, so rows always carry sized, centered content (issue #1666).
95
113
  if (isSvg) {
96
114
  return (
97
115
  <Avatar
@@ -99,6 +117,7 @@ export const ProfileAvatar = ({
99
117
  className={rootClassName}
100
118
  style={{ width: px, height: px }}
101
119
  >
120
+ {initialsTile}
102
121
  <SvgImage
103
122
  uri={avatarSource.uri}
104
123
  className={cn('h-full w-full', roundedClass)}
@@ -114,6 +133,7 @@ export const ProfileAvatar = ({
114
133
  className={rootClassName}
115
134
  style={{ width: px, height: px }}
116
135
  >
136
+ {initialsTile}
117
137
  <AvatarImage
118
138
  source={avatarSource}
119
139
  className={cn('h-full w-full', roundedClass)}
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Regression tests for `ui/avatar`'s paint-over guarantee (issue #1666,
3
+ * round-20 review item 2).
4
+ *
5
+ * The avatar underlays (ProfileAvatar / GroupAvatar initials tiles) rely on a
6
+ * *loaded* image covering them: `AvatarImage` must keep a full-size base
7
+ * `className` (`aspect-square h-full w-full`, merged with any passed
8
+ * `className` via the real `cn`/twMerge) and forward `style` to the primitive
9
+ * image. A regression that drops the size classes or `style` renders a loaded
10
+ * image at zero size — leaving only the underlay visible — which silently
11
+ * reintroduces the exact reported symptom. These tests fail on that.
12
+ *
13
+ * `./svg-image` is mocked to a marker so the SVG branch is deterministic
14
+ * (the real `SvgImage` only paints after an async file read); the size
15
+ * `className` under test is computed in `avatar.tsx` and asserted on the prop
16
+ * it passes down. The real `isSvgUrl` (Jest source convention) decides the
17
+ * SVG-vs-raster branch.
18
+ */
19
+
20
+ const React = require('react');
21
+ const ReactTestRenderer = require('react-test-renderer');
22
+
23
+ const MockPrimitiveImage = (props: {
24
+ source?: unknown;
25
+ className?: string;
26
+ style?: unknown;
27
+ }) =>
28
+ React.createElement('PrimitiveImage', {
29
+ source: props.source,
30
+ className: props.className,
31
+ style: props.style,
32
+ });
33
+ const MockSvgImage = (props: {
34
+ uri?: string;
35
+ className?: string;
36
+ resizeMode?: string;
37
+ }) =>
38
+ React.createElement('SvgImage', {
39
+ uri: props.uri,
40
+ className: props.className,
41
+ resizeMode: props.resizeMode,
42
+ });
43
+
44
+ jest.mock('react-native', () => ({ View: 'view', Image: 'image' }));
45
+ jest.mock('@rn-primitives/avatar', () => ({
46
+ Root: 'avatar-root',
47
+ Image: MockPrimitiveImage,
48
+ Fallback: 'avatar-fallback',
49
+ }));
50
+ jest.mock('../../hooks/use-cached-media-uri', () => ({
51
+ useCachedMediaUri: (uri?: string) =>
52
+ uri ? `file:///cache/${uri}` : undefined,
53
+ isLocalMediaUri: () => false,
54
+ }));
55
+ jest.mock('./svg-image', () => ({ SvgImage: MockSvgImage }));
56
+
57
+ // Real merge semantics: the real lib/utils drags in @openpeepshq/common (ESM
58
+ // dist) via its import graph, so recreate cn exactly (clsx + twMerge) here.
59
+ // That is what the assertions exercise — that the full-size base classes
60
+ // survive the real twMerge with the passed className.
61
+ const { clsx } = require('clsx');
62
+ const { twMerge } = require('tailwind-merge');
63
+ jest.mock('../../lib/utils', () => ({
64
+ cn: (...inputs: Array<string | undefined>) => twMerge(clsx(inputs)),
65
+ }));
66
+
67
+ // Real URL helper (mapped through the repo's Jest source convention for
68
+ // `@openpeepshq/react`) — the SVG-vs-raster branch is part of what is pinned.
69
+ jest.mock('@openpeepshq/react', () => ({
70
+ isSvgUrl: require('../../../../react/src/lib/svgCover').isSvgUrl,
71
+ }));
72
+
73
+ const { AvatarImage } = require('./avatar');
74
+
75
+ const renderImage = (props: {
76
+ source?: unknown;
77
+ className?: string;
78
+ style?: unknown;
79
+ }) => {
80
+ let tree: ReturnType<typeof ReactTestRenderer.create>;
81
+ ReactTestRenderer.act(() => {
82
+ tree = ReactTestRenderer.create(React.createElement(AvatarImage, props));
83
+ });
84
+ return tree;
85
+ };
86
+
87
+ describe('ui/avatar AvatarImage size/style pass-through (issue #1666 round-20 #2)', () => {
88
+ it('keeps the full-size base classes, merges the passed className, and forwards style (raster branch)', () => {
89
+ const tree = renderImage({
90
+ source: { uri: 'https://cdn.example/avatars/x.png' },
91
+ className: 'rounded-full',
92
+ style: { width: 40, height: 40 },
93
+ });
94
+ const image = tree.root.findByType('PrimitiveImage');
95
+ // The cached URI (useCachedMediaUri) is what a loaded image renders with.
96
+ expect(image.props.source).toEqual({
97
+ uri: 'file:///cache/https://cdn.example/avatars/x.png',
98
+ });
99
+ // style must reach the primitive image (dropping it regresses the underlay
100
+ // paint-over to a zero-size overlay).
101
+ expect(image.props.style).toEqual({ width: 40, height: 40 });
102
+ // The full-size base classes survive the real cn/twMerge merge with the
103
+ // passed className — nothing size-related is dropped.
104
+ expect(image.props.className).toContain('h-full');
105
+ expect(image.props.className).toContain('w-full');
106
+ expect(image.props.className).toContain('rounded-full');
107
+ expect(tree.root.findAllByType('SvgImage')).toHaveLength(0);
108
+ });
109
+
110
+ it('keeps the full-size base classes and merges the passed className (SVG branch)', () => {
111
+ const tree = renderImage({
112
+ source: { uri: 'https://cdn.example/avatars/x.svg' },
113
+ className: 'rounded-full',
114
+ });
115
+ const svgImage = tree.root.findByType('SvgImage');
116
+ expect(svgImage.props.uri).toBe('https://cdn.example/avatars/x.svg');
117
+ expect(svgImage.props.resizeMode).toBe('cover');
118
+ expect(svgImage.props.className).toContain('h-full');
119
+ expect(svgImage.props.className).toContain('w-full');
120
+ expect(svgImage.props.className).toContain('rounded-full');
121
+ expect(tree.root.findAllByType('PrimitiveImage')).toHaveLength(0);
122
+ });
123
+ });