@openpeepshq/rn-components 0.10.0 → 0.10.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.10.0",
3
+ "version": "0.10.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",
@@ -62,7 +62,7 @@
62
62
  "@hookform/resolvers": "^5.4.2",
63
63
  "@livekit/react-native": "2.11.0",
64
64
  "@livekit/react-native-krisp-noise-filter": "^0.0.3",
65
- "@livekit/react-native-webrtc": "144.1.0",
65
+ "@livekit/react-native-webrtc": "144.1.1",
66
66
  "@notifee/react-native": "^9.1.8",
67
67
  "@react-native-async-storage/async-storage": "^2.1.1",
68
68
  "@react-native-clipboard/clipboard": "^1.16.1",
@@ -98,7 +98,7 @@
98
98
  "clsx": "^2.1.1",
99
99
  "date-fns": "^4.1.0",
100
100
  "i18next": "^24.2.3",
101
- "i18next-http-backend": "^3.0.2",
101
+ "i18next-http-backend": "^3.0.6",
102
102
  "js-base64": "^3.7.7",
103
103
  "livekit-client": "2.19.2",
104
104
  "lucide-react-native": "^0.474.0",
@@ -142,7 +142,7 @@
142
142
  "timezones-list": "^3.1.0",
143
143
  "validator": "^13.15.23",
144
144
  "zustand": "^5.0.3",
145
- "@openpeepshq/common": "^0.6.0",
145
+ "@openpeepshq/common": "^0.6.1",
146
146
  "@openpeepshq/react": "^0.10.0"
147
147
  },
148
148
  "devDependencies": {
@@ -173,7 +173,7 @@
173
173
  "babel-plugin-module-resolver": "^5.0.2",
174
174
  "commitlint": "^17.0.2",
175
175
  "del-cli": "^5.1.0",
176
- "eslint": "^10.1.0",
176
+ "eslint": "^10.14.0",
177
177
  "eslint-config-prettier": "^9.1.0",
178
178
  "eslint-plugin-prettier": "^5.0.1",
179
179
  "eslint-plugin-react-hooks": "^5.2.0",
@@ -184,7 +184,6 @@
184
184
  "react-test-renderer": "19.2.3",
185
185
  "release-it": "^17.10.0",
186
186
  "ts-jest": "^29.3.4",
187
- "turbo": "^1.10.7",
188
187
  "typescript": "^6.0.2",
189
188
  "@eslint/js": "^9.17.0"
190
189
  },
@@ -1,11 +1,15 @@
1
1
  import React from 'react';
2
2
  import { View } from 'react-native';
3
+ import { useTranslation } from 'react-i18next';
3
4
  import type { PublicPost } from '@openpeepshq/common/types';
4
- import { useCurrentProfile } from '@openpeepshq/react';
5
+ import { useCurrentProfile, usePostReactionToggle } from '@openpeepshq/react';
5
6
  import { useOpenPeepsTheme } from '../../theme/OpenPeepsThemeProvider';
6
7
  import { FeedPostContent } from '../post/FeedPostContent';
7
8
  import { UnreadPostIndicator } from '../post/pieces/UnreadPostIndicator';
8
9
  import { hexWithOpacity } from '../../theme/utils';
10
+ import { Button } from '../ui/button';
11
+ import { ThemedText } from '../ui/themed-text';
12
+ import { ThumbsUpIcon } from '../icons/index';
9
13
 
10
14
  export interface ConversationMessageBubbleProps {
11
15
  message: PublicPost;
@@ -18,7 +22,10 @@ export const ConversationMessageBubble = ({
18
22
  }: ConversationMessageBubbleProps) => {
19
23
  const me = useCurrentProfile();
20
24
  const theme = useOpenPeepsTheme();
25
+ const { t } = useTranslation();
21
26
  const mine = message.profile.id === me?.id;
27
+ const { iReacted, canReact, toggleReaction } = usePostReactionToggle(message);
28
+ const reactionCount = message.reactions?.length ?? 0;
22
29
 
23
30
  // NativeWind v4 can't apply `/N` opacity to CSS-variable colors (e.g.
24
31
  // `bg-primary/10`), so we use an inline rgba style for own-message bubbles.
@@ -39,6 +46,34 @@ export const ConversationMessageBubble = ({
39
46
  style={bubbleStyle}
40
47
  >
41
48
  <FeedPostContent post={message} />
49
+ {me && canReact ? (
50
+ <View
51
+ className={
52
+ mine ? 'mt-2 flex-row justify-end' : 'mt-2 flex-row justify-start'
53
+ }
54
+ >
55
+ <Button
56
+ variant="ghost"
57
+ onPress={() => void toggleReaction()}
58
+ accessibilityLabel={t('posts.actions.react')}
59
+ className="items-center gap-1 native:px-2 native:py-1"
60
+ >
61
+ <ThumbsUpIcon
62
+ size={16}
63
+ className={iReacted ? 'text-primary' : 'text-muted-foreground'}
64
+ />
65
+ {reactionCount > 0 ? (
66
+ <ThemedText
67
+ className={`text-xs ${
68
+ iReacted ? 'text-primary' : 'text-muted-foreground'
69
+ }`}
70
+ >
71
+ {reactionCount}
72
+ </ThemedText>
73
+ ) : null}
74
+ </Button>
75
+ </View>
76
+ ) : null}
42
77
  </View>
43
78
  {!mine ? (
44
79
  <UnreadPostIndicator
@@ -17,10 +17,20 @@ export const UpdatingDate = ({
17
17
  const [formattedDate, setFormattedDate] = React.useState(formatter(date));
18
18
 
19
19
  useEffect(() => {
20
- const interval = setInterval(() => {
20
+ // Tick when the displayed value can change: at the next minute
21
+ // boundary of the time since `date`, instead of polling every 60s.
22
+ const dateMs =
23
+ date instanceof Date ? date.getTime() : new Date(date).getTime();
24
+ setFormattedDate(formatter(date));
25
+ if (!Number.isFinite(dateMs)) return;
26
+ const msUntilNextMinute = () => 60_000 - ((Date.now() - dateMs) % 60_000);
27
+ let handle: ReturnType<typeof setTimeout> | undefined;
28
+ const tick = () => {
21
29
  setFormattedDate(formatter(date));
22
- }, 60000);
23
- return () => clearInterval(interval);
30
+ handle = setTimeout(tick, msUntilNextMinute());
31
+ };
32
+ handle = setTimeout(tick, msUntilNextMinute());
33
+ return () => clearTimeout(handle);
24
34
  }, [date, formatter]);
25
35
 
26
36
  return (
@@ -11,7 +11,7 @@ import {
11
11
  import Toast from 'react-native-toast-message';
12
12
  import { useTranslation } from 'react-i18next';
13
13
  import {
14
- parseParticipantMetadata,
14
+ participantTileProfile,
15
15
  useCurrentProfile,
16
16
  useJamContext,
17
17
  useJamEventsContext,
@@ -177,7 +177,7 @@ const JamParticipantOverlay = ({
177
177
  const micOn = participant.isMicrophoneEnabled;
178
178
  const handUp = raisedHands.has(participant.identity);
179
179
  const handRaiseSound = useRef<Sound | null>(null);
180
- const profile = parseParticipantMetadata(participant.metadata).profile;
180
+ const profile = participantTileProfile(participant, me);
181
181
  const isModerator = jam.moderators.includes(participant.identity);
182
182
  const viewerIsModerator = !!me && jam.moderators.includes(me.id);
183
183
  const iconSize = compact ? 12 : 16;
@@ -285,8 +285,9 @@ export const JamCallParticipant = ({
285
285
  onToggleSpotlight,
286
286
  }: JamCallParticipantProps) => {
287
287
  const { t } = useTranslation();
288
+ const me = useCurrentProfile();
288
289
  const participant = trackRef.participant;
289
- const profile = parseParticipantMetadata(participant.metadata).profile;
290
+ const profile = participantTileProfile(participant, me);
290
291
  const connectionLost = useConnectionLost(participant);
291
292
  const speaking = useIsSpeaking(participant);
292
293
  // React Native's RTCView only re-resolves its media stream when the
@@ -239,6 +239,8 @@ export const useNativeRouterAdapter = (): RouterAdapter =>
239
239
  () => ({
240
240
  pathname: '',
241
241
  searchParams: new URLSearchParams(),
242
+ // Native has no URL bar to keep in sync, so there is no query to write.
243
+ setSearchParams: () => {},
242
244
  hrefOf: () => '',
243
245
  match: () => null,
244
246
  navigate: (target) => {
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Tests for the RemotePreviewLink click-to-load behavior and the WebView
3
+ * navigation guard.
4
+ *
5
+ * The player (WebView) must not mount until the user taps the card, and
6
+ * sub-frame loads inside the player must not be hijacked into the system
7
+ * browser (players spawn cross-origin child frames on iOS).
8
+ */
9
+
10
+ const React = require('react');
11
+ const ReactTestRenderer = require('react-test-renderer');
12
+
13
+ jest.mock('react-native', () => {
14
+ const View = ({ children }: { children?: unknown }) =>
15
+ React.createElement('View', null, children);
16
+ const Text = ({ children }: { children?: unknown }) =>
17
+ React.createElement('Text', null, children);
18
+ const TouchableOpacity = (props: {
19
+ children?: unknown;
20
+ onPress?: () => void;
21
+ }) =>
22
+ React.createElement(
23
+ 'TouchableOpacity',
24
+ { testID: 'pressable', ...props },
25
+ props.children
26
+ );
27
+ const ActivityIndicator = () => React.createElement('ActivityIndicator');
28
+ const Linking = { openURL: jest.fn() };
29
+ const StyleSheet = { create: (s: unknown) => s };
30
+ return {
31
+ View,
32
+ Text,
33
+ TouchableOpacity,
34
+ ActivityIndicator,
35
+ Linking,
36
+ StyleSheet,
37
+ };
38
+ });
39
+
40
+ // The built common package ships ESM which Jest's node transform doesn't
41
+ // cover, so mirror the two helpers the component needs (same approach as
42
+ // html.test.tsx). videoEmbedForUrl must stay in sync with
43
+ // platform/common/src/lib/videoEmbed.ts.
44
+ jest.mock('@openpeepshq/common/lib', () => {
45
+ const YOUTUBE_ID_RE = /^[A-Za-z0-9_-]{6,15}$/;
46
+ const VIMEO_ID_RE = /^\d{6,}$/;
47
+ const YOUTUBE_ORIGIN = 'https://www.youtube-nocookie.com';
48
+ const VIMEO_ORIGIN = 'https://player.vimeo.com';
49
+
50
+ const parseYouTubeStart = (raw: string): number | undefined => {
51
+ const trimmed = raw.trim();
52
+ if (trimmed === '') return undefined;
53
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
54
+ const compact = trimmed.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);
55
+ if (compact) {
56
+ const [, hours, minutes, seconds] = compact;
57
+ if (!hours && !minutes && !seconds) return undefined;
58
+ return (
59
+ Number(hours ?? 0) * 3600 +
60
+ Number(minutes ?? 0) * 60 +
61
+ Number(seconds ?? 0)
62
+ );
63
+ }
64
+ const parts = trimmed.split(':');
65
+ if (parts.length > 3 || parts.some((part) => !/^\d+$/.test(part))) {
66
+ return undefined;
67
+ }
68
+ return parts.reduce((total, part) => total * 60 + Number(part), 0);
69
+ };
70
+
71
+ const videoEmbedForUrl = (
72
+ url: string
73
+ ):
74
+ | {
75
+ provider: string;
76
+ embedUrl: string;
77
+ origin: string;
78
+ }
79
+ | undefined => {
80
+ let parsed: URL;
81
+ try {
82
+ parsed = new URL(url);
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ const host = parsed.hostname.replace(/^(www|m)\./, '');
87
+
88
+ const youtubeEmbed = (id: string) => {
89
+ const rawStart =
90
+ parsed.searchParams.get('t') ?? parsed.searchParams.get('start');
91
+ const start = rawStart ? parseYouTubeStart(rawStart) : undefined;
92
+ return {
93
+ provider: 'youtube',
94
+ embedUrl:
95
+ `${YOUTUBE_ORIGIN}/embed/${id}` +
96
+ (start !== undefined && start > 0 ? `?start=${start}` : ''),
97
+ origin: YOUTUBE_ORIGIN,
98
+ };
99
+ };
100
+
101
+ if (host === 'youtu.be') {
102
+ const id = parsed.pathname.split('/')[1] ?? '';
103
+ return YOUTUBE_ID_RE.test(id) ? youtubeEmbed(id) : undefined;
104
+ }
105
+
106
+ if (host === 'youtube.com') {
107
+ const segments = parsed.pathname.split('/').filter(Boolean);
108
+ let id: string | undefined;
109
+ if (segments[0] === 'watch') {
110
+ id = parsed.searchParams.get('v') ?? undefined;
111
+ } else if (segments[0] === 'shorts' || segments[0] === 'embed') {
112
+ id = segments[1];
113
+ }
114
+ return id && YOUTUBE_ID_RE.test(id) ? youtubeEmbed(id) : undefined;
115
+ }
116
+
117
+ if (host === 'vimeo.com' || host === 'player.vimeo.com') {
118
+ const segments = parsed.pathname.split('/').filter(Boolean);
119
+ let id: string | undefined;
120
+ let hash: string | undefined;
121
+ if (host === 'player.vimeo.com') {
122
+ if (segments[0] === 'video') {
123
+ id = segments[1];
124
+ hash = parsed.searchParams.get('h') ?? undefined;
125
+ }
126
+ } else if (segments.length === 1) {
127
+ id = segments[0];
128
+ } else if (segments.length === 2 && VIMEO_ID_RE.test(segments[0])) {
129
+ id = segments[0];
130
+ hash = segments[1];
131
+ } else if (segments.length === 3 && segments[0] === 'channels') {
132
+ id = segments[2];
133
+ } else if (
134
+ segments.length === 4 &&
135
+ segments[0] === 'groups' &&
136
+ segments[2] === 'videos'
137
+ ) {
138
+ id = segments[3];
139
+ }
140
+ if (!id || !VIMEO_ID_RE.test(id)) return undefined;
141
+ return {
142
+ provider: 'vimeo',
143
+ embedUrl:
144
+ `${VIMEO_ORIGIN}/video/${id}?dnt=1` + (hash ? `&h=${hash}` : ''),
145
+ origin: VIMEO_ORIGIN,
146
+ };
147
+ }
148
+
149
+ return undefined;
150
+ };
151
+
152
+ return {
153
+ videoEmbedForUrl,
154
+ isExternalLink: (href: string, origin?: string): boolean => {
155
+ if (!href || /^(mailto:|tel:|#)/.test(href)) return false;
156
+ if (href.startsWith('/') && !href.startsWith('//')) return false;
157
+ if (!origin) return !href.startsWith('/');
158
+ try {
159
+ return new URL(href, origin).origin !== origin;
160
+ } catch {
161
+ return !href.startsWith('/');
162
+ }
163
+ },
164
+ };
165
+ });
166
+
167
+ jest.mock('@openpeepshq/react', () => ({
168
+ useOpenpeeps: () => ({
169
+ openpeepsApi: {
170
+ usePreviewLink: () => mockPreviewState,
171
+ },
172
+ }),
173
+ recordOutboundClick: jest.fn(),
174
+ }));
175
+
176
+ jest.mock('../ui/themed-text', () => ({
177
+ ThemedText: (props: unknown) => React.createElement('Text', props),
178
+ }));
179
+
180
+ jest.mock('../custom/common/index', () => ({
181
+ CachedImage: () =>
182
+ React.createElement('CachedImage', { testID: 'cached-image' }),
183
+ }));
184
+
185
+ jest.mock('../post/VideoPlayOverlay', () => ({
186
+ VideoPlayOverlay: ({ video }: { video: boolean }) =>
187
+ video ? React.createElement('View', { testID: 'play-overlay' }) : null,
188
+ }));
189
+
190
+ jest.mock('react-native-webview', () => {
191
+ const { View } = require('react-native');
192
+ class WebView extends React.Component {
193
+ render() {
194
+ return React.createElement(View, { testID: 'webview-mock' });
195
+ }
196
+ }
197
+ return { WebView };
198
+ });
199
+
200
+ const { Linking } = require('react-native');
201
+ const { recordOutboundClick } = require('@openpeepshq/react');
202
+ const { WebView } = require('react-native-webview');
203
+ const { RemotePreviewLink } = require('./RemotePreviewLink');
204
+
205
+ const YOUTUBE_URL = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
206
+ const YOUTUBE_EMBED = 'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ';
207
+
208
+ let mockPreviewState: {
209
+ data?: { data?: { title?: string; description?: string; image?: string } };
210
+ isLoading: boolean;
211
+ isError: boolean;
212
+ };
213
+
214
+ const render = (url: string) => {
215
+ let tree: ReturnType<typeof ReactTestRenderer.create>;
216
+ ReactTestRenderer.act(() => {
217
+ tree = ReactTestRenderer.create(
218
+ React.createElement(RemotePreviewLink, { url })
219
+ );
220
+ });
221
+ return tree;
222
+ };
223
+
224
+ describe('RemotePreviewLink', () => {
225
+ beforeEach(() => {
226
+ mockPreviewState = {
227
+ // apiHook shape: result.data is the envelope, result.data.data the
228
+ // payload (same as the web component's previewQuery.data?.data).
229
+ data: {
230
+ data: {
231
+ title: 'Test video',
232
+ description: 'A test video',
233
+ image: 'https://example.com/thumb.jpg',
234
+ },
235
+ },
236
+ isLoading: false,
237
+ isError: false,
238
+ };
239
+ Linking.openURL.mockClear();
240
+ recordOutboundClick.mockClear();
241
+ });
242
+
243
+ it('renders the link card for non-video URLs without a WebView', () => {
244
+ const tree = render('https://example.com/article');
245
+ expect(tree.root.findAllByType(WebView)).toHaveLength(0);
246
+ expect(tree.root.findAllByProps({ testID: 'play-overlay' })).toHaveLength(
247
+ 0
248
+ );
249
+ expect(tree.root.findAllByProps({ testID: 'cached-image' })).toHaveLength(
250
+ 1
251
+ );
252
+ tree.unmount();
253
+ });
254
+
255
+ it('opens the URL in the browser when a non-video card is pressed', () => {
256
+ const tree = render('https://example.com/article');
257
+ const pressable = tree.root.findByProps({ testID: 'pressable' });
258
+ ReactTestRenderer.act(() => {
259
+ pressable.props.onPress();
260
+ });
261
+ expect(Linking.openURL).toHaveBeenCalledWith('https://example.com/article');
262
+ expect(recordOutboundClick).toHaveBeenCalledWith(
263
+ 'https://example.com/article'
264
+ );
265
+ tree.unmount();
266
+ });
267
+
268
+ it('shows the card with a play overlay for video URLs and no WebView', () => {
269
+ const tree = render(YOUTUBE_URL);
270
+ expect(tree.root.findAllByType(WebView)).toHaveLength(0);
271
+ expect(tree.root.findAllByProps({ testID: 'play-overlay' })).toHaveLength(
272
+ 1
273
+ );
274
+ const texts = tree.root
275
+ .findAllByType('Text')
276
+ .map((node: { props: { children?: unknown } }) => node.props.children);
277
+ expect(texts).toContain('Test video');
278
+ tree.unmount();
279
+ });
280
+
281
+ it('mounts the WebView only after the card is pressed', () => {
282
+ const tree = render(YOUTUBE_URL);
283
+ const pressable = tree.root.findByProps({ testID: 'pressable' });
284
+ ReactTestRenderer.act(() => {
285
+ pressable.props.onPress();
286
+ });
287
+ const webView = tree.root.findByType(WebView);
288
+ expect(webView.props.source.uri).toBe(YOUTUBE_EMBED);
289
+ tree.unmount();
290
+ });
291
+
292
+ describe('WebView navigation guard', () => {
293
+ const mountedHandler = () => {
294
+ const tree = render(YOUTUBE_URL);
295
+ const pressable = tree.root.findByProps({ testID: 'pressable' });
296
+ ReactTestRenderer.act(() => {
297
+ pressable.props.onPress();
298
+ });
299
+ const handler =
300
+ tree.root.findByType(WebView).props.onShouldStartLoadWithRequest;
301
+ return { tree, handler };
302
+ };
303
+
304
+ it('lets sub-frame loads stay in the WebView', () => {
305
+ const { tree, handler } = mountedHandler();
306
+ expect(
307
+ handler({
308
+ url: 'https://ads.example.com/track',
309
+ isTopFrame: false,
310
+ navigationType: 'other',
311
+ })
312
+ ).toBe(true);
313
+ expect(Linking.openURL).not.toHaveBeenCalled();
314
+ tree.unmount();
315
+ });
316
+
317
+ it('lets non-click top-frame navigations stay in the WebView', () => {
318
+ const { tree, handler } = mountedHandler();
319
+ expect(
320
+ handler({
321
+ url: `${YOUTUBE_EMBED}?autoplay=1`,
322
+ isTopFrame: true,
323
+ navigationType: 'other',
324
+ })
325
+ ).toBe(true);
326
+ expect(Linking.openURL).not.toHaveBeenCalled();
327
+ tree.unmount();
328
+ });
329
+
330
+ it('keeps same-origin top-frame clicks in the WebView', () => {
331
+ const { tree, handler } = mountedHandler();
332
+ expect(
333
+ handler({
334
+ url: 'https://www.youtube-nocookie.com/embed/other',
335
+ isTopFrame: true,
336
+ navigationType: 'click',
337
+ })
338
+ ).toBe(true);
339
+ expect(Linking.openURL).not.toHaveBeenCalled();
340
+ tree.unmount();
341
+ });
342
+
343
+ it('opens external top-frame clicks in the browser', () => {
344
+ const { tree, handler } = mountedHandler();
345
+ expect(
346
+ handler({
347
+ url: 'https://twitter.com/home',
348
+ isTopFrame: true,
349
+ navigationType: 'click',
350
+ })
351
+ ).toBe(false);
352
+ expect(Linking.openURL).toHaveBeenCalledWith('https://twitter.com/home');
353
+ tree.unmount();
354
+ });
355
+ });
356
+ });
@@ -1,9 +1,12 @@
1
- import React from 'react';
1
+ import React, { useState } from 'react';
2
2
  import { View, TouchableOpacity, Linking } from 'react-native';
3
+ import { WebView } from 'react-native-webview';
3
4
  import { ThemedText as Text } from '../ui/themed-text';
4
5
  import { useOpenpeeps, recordOutboundClick } from '@openpeepshq/react';
6
+ import { isExternalLink, videoEmbedForUrl } from '@openpeepshq/common/lib';
5
7
  import { ActivityIndicator } from 'react-native';
6
8
  import { CachedImage } from '../custom/common/index';
9
+ import { VideoPlayOverlay } from '../post/VideoPlayOverlay';
7
10
 
8
11
  interface RemotePreviewLinkProps {
9
12
  url: string;
@@ -11,6 +14,10 @@ interface RemotePreviewLinkProps {
11
14
 
12
15
  export const RemotePreviewLink = ({ url }: RemotePreviewLinkProps) => {
13
16
  const { openpeepsApi } = useOpenpeeps();
17
+ const embed = videoEmbedForUrl(url);
18
+ // Click-to-load: the server-fetched card (no third-party request) is the
19
+ // default view; the WebView mounts only after an explicit tap.
20
+ const [loadedUrl, setLoadedUrl] = useState<string | null>(null);
14
21
 
15
22
  const {
16
23
  data: linkPreview,
@@ -19,10 +26,40 @@ export const RemotePreviewLink = ({ url }: RemotePreviewLinkProps) => {
19
26
  } = openpeepsApi.usePreviewLink(url);
20
27
 
21
28
  const handlePress = () => {
29
+ if (embed) {
30
+ setLoadedUrl(url);
31
+ return;
32
+ }
22
33
  recordOutboundClick(url);
23
34
  Linking.openURL(url);
24
35
  };
25
36
 
37
+ if (embed && loadedUrl === url) {
38
+ // Same pattern as the markdown iframe renderer: allow same-origin
39
+ // navigations (e.g. YouTube play state), open cross-origin in browser.
40
+ return (
41
+ <View className="my-2 w-full">
42
+ <WebView
43
+ source={{ uri: embed.embedUrl }}
44
+ style={{ width: '100%', aspectRatio: 16 / 9, borderRadius: 8 }}
45
+ scrollEnabled={false}
46
+ onShouldStartLoadWithRequest={(nav) => {
47
+ // Sub-frames (players spawn cross-origin child frames on iOS)
48
+ // must not be hijacked into the browser.
49
+ if (!nav.isTopFrame || nav.navigationType !== 'click') {
50
+ return true;
51
+ }
52
+ if (isExternalLink(nav.url, embed.origin)) {
53
+ Linking.openURL(nav.url);
54
+ return false;
55
+ }
56
+ return true;
57
+ }}
58
+ />
59
+ </View>
60
+ );
61
+ }
62
+
26
63
  if (isLoading) {
27
64
  return (
28
65
  <View className="w-full">
@@ -40,36 +77,37 @@ export const RemotePreviewLink = ({ url }: RemotePreviewLinkProps) => {
40
77
  return (
41
78
  <TouchableOpacity onPress={handlePress} className="w-full no-underline">
42
79
  <View className="card w-full">
43
- {url && linkPreview.data && (
44
- <View className="flex w-full flex-row items-center gap-4 p-2">
45
- {image && (
46
- <View className="flex h-32 w-32 flex-shrink-0 items-center justify-center">
80
+ <View className="flex w-full flex-row items-center gap-4 p-2">
81
+ {(image || embed) && (
82
+ <View className="relative flex h-32 w-32 flex-shrink-0 items-center justify-center">
83
+ {image && (
47
84
  <CachedImage
48
85
  url={image}
49
86
  className="h-full w-full rounded-md object-cover object-center"
50
87
  resizeMode="cover"
51
88
  />
52
- </View>
53
- )}
54
- <View
55
- className={`flex ${
56
- image ? 'w-32 flex-1' : 'w-full'
57
- } flex-col items-start justify-start gap-y-3`}
58
- >
59
- <View className="w-fit">
60
- <Text className="text-foreground text-sm font-thin sm:text-xs">
61
- {new URL(url).hostname}
62
- </Text>
63
- </View>
64
- <View className="w-fit font-bold">
65
- <Text className="font-bold">{title ?? ''}</Text>
66
- </View>
67
- <View className="text-foreground w-full truncate text-sm font-thin">
68
- <Text>{description ?? ''}</Text>
69
- </View>
89
+ )}
90
+ <VideoPlayOverlay video={Boolean(embed)} />
91
+ </View>
92
+ )}
93
+ <View
94
+ className={`flex ${
95
+ image || embed ? 'w-32 flex-1' : 'w-full'
96
+ } flex-col items-start justify-start gap-y-3`}
97
+ >
98
+ <View className="w-fit">
99
+ <Text className="text-foreground text-sm font-thin sm:text-xs">
100
+ {new URL(url).hostname}
101
+ </Text>
102
+ </View>
103
+ <View className="w-fit font-bold">
104
+ <Text className="font-bold">{title ?? ''}</Text>
105
+ </View>
106
+ <View className="text-foreground w-full truncate text-sm font-thin">
107
+ <Text>{description ?? ''}</Text>
70
108
  </View>
71
109
  </View>
72
- )}
110
+ </View>
73
111
  </View>
74
112
  </TouchableOpacity>
75
113
  );
@@ -33,6 +33,7 @@ const Tree = ({
33
33
  counts,
34
34
  expanded,
35
35
  onToggle,
36
+ t,
36
37
  }: {
37
38
  nodes: CategoryNode[];
38
39
  selected: string[];
@@ -40,6 +41,7 @@ const Tree = ({
40
41
  counts: Map<string, number>;
41
42
  expanded: Set<string>;
42
43
  onToggle: (nodeKey: string) => void;
44
+ t: ReturnType<typeof useTranslation>['t'];
43
45
  }) => (
44
46
  <View className="gap-y-1">
45
47
  {nodes.map((node) => {
@@ -54,6 +56,16 @@ const Tree = ({
54
56
  <Pressable
55
57
  onPress={hasChildren ? () => onToggle(nodeKey) : undefined}
56
58
  className={hasChildren ? '' : 'invisible'}
59
+ accessibilityRole="button"
60
+ accessibilityLabel={
61
+ isExpanded
62
+ ? t('resources.library.collapseFolder', {
63
+ defaultValue: 'Collapse folder',
64
+ })
65
+ : t('resources.library.expandFolder', {
66
+ defaultValue: 'Expand folder',
67
+ })
68
+ }
57
69
  >
58
70
  <ChevronRightIcon
59
71
  size={16}
@@ -86,6 +98,7 @@ const Tree = ({
86
98
  counts={counts}
87
99
  expanded={expanded}
88
100
  onToggle={onToggle}
101
+ t={t}
89
102
  />
90
103
  </View>
91
104
  ) : null}
@@ -266,6 +279,17 @@ export const ResourceLibrary = ({ groupId }: ResourceLibraryProps) => {
266
279
  <Pressable
267
280
  onPress={() => library.setHierarchy(!library.hierarchy)}
268
281
  className="ml-auto"
282
+ accessibilityRole="button"
283
+ accessibilityLabel={t(
284
+ library.hierarchy
285
+ ? 'resources.library.hideFolderTree'
286
+ : 'resources.library.showFolderTree',
287
+ {
288
+ defaultValue: library.hierarchy
289
+ ? 'Hide folder tree'
290
+ : 'Show folder tree',
291
+ }
292
+ )}
269
293
  >
270
294
  {library.hierarchy ? (
271
295
  <ChevronDownIcon size={20} className="text-muted-foreground" />
@@ -283,6 +307,7 @@ export const ResourceLibrary = ({ groupId }: ResourceLibraryProps) => {
283
307
  counts={collectionCounts}
284
308
  expanded={expanded}
285
309
  onToggle={toggleNode}
310
+ t={t}
286
311
  />
287
312
  </View>
288
313
  ) : null}
@@ -4,19 +4,30 @@ import {
4
4
  ScrollView,
5
5
  ActivityIndicator,
6
6
  } from 'react-native';
7
- import React, { useEffect } from 'react';
7
+ import React, { useCallback, useEffect, useRef } from 'react';
8
+ import { BottomSheetModal } from '@gorhom/bottom-sheet';
8
9
  import { ThemedView } from '../../components/ui/themed-view';
9
10
  import { MainScreenProps } from '../../components/navigation/types/index';
10
11
  import { useNewConversationStore } from '../../stores/useNewConversationStore';
11
12
  import { TouchableOpacity } from 'react-native';
12
13
  import { useSetPageHeader } from '../../components/layout';
13
- import { SendHorizonalIcon } from '../../components/icons/index';
14
- import { useCreateConversation, useOpenpeeps } from '@openpeepshq/react';
14
+ import { ImageIcon, SendHorizonalIcon } from '../../components/icons/index';
15
+ import {
16
+ canSendDmMessage,
17
+ useCreateConversation,
18
+ useOpenpeeps,
19
+ DM_MAX_ATTACHMENTS,
20
+ } from '@openpeepshq/react';
15
21
  import { ThemedText } from '../../components/ui/themed-text';
16
- import { Profile, PublicProfile } from '@openpeepshq/common';
22
+ import { MediaAttachment, Profile, PublicProfile } from '@openpeepshq/common';
23
+ import { ImagePickerSheet } from '../../components/custom/index';
24
+ import { ComposeAttachments } from '../../components/post/post-form/ComposeAttachments';
17
25
  import { OpenpeepsMarkdownInput } from '../../components/post/post-form/OpenpeepsMarkdownInput';
26
+ import { Button } from '../../components/ui/button';
18
27
  import { useTranslation } from 'react-i18next';
19
28
  import { maxContentLength } from '../../lib/utils';
29
+ import { checkMediaPermissions } from '../../lib/media-permissions';
30
+ import { isAttachmentProcessing } from '../../lib/post';
20
31
 
21
32
  type DraftMessageProps = MainScreenProps<'DraftMessage'>;
22
33
 
@@ -25,18 +36,40 @@ export const DraftMessage = ({ navigation }: DraftMessageProps) => {
25
36
  const { members, clearMembers, contnt, setContt } = useNewConversationStore();
26
37
  const { currentProfile } = useOpenpeeps();
27
38
  const scrollViewRef = React.useRef<ScrollView>(null);
28
- const { message, setMessage, send, submitting } = useCreateConversation({
29
- profiles: members as PublicProfile[],
30
- message: contnt,
31
- skipProfileSelection: true,
32
- onClose: () => {
33
- setContt('');
34
- clearMembers();
35
- navigation.pop();
36
- navigation.pop();
37
- },
39
+ const { message, setMessage, attachments, setAttachments, send, submitting } =
40
+ useCreateConversation({
41
+ profiles: members as PublicProfile[],
42
+ message: contnt,
43
+ skipProfileSelection: true,
44
+ onClose: () => {
45
+ setContt('');
46
+ clearMembers();
47
+ navigation.pop();
48
+ navigation.pop();
49
+ },
50
+ });
51
+ const imagePickerRef = useRef<BottomSheetModal>(null);
52
+ const canSend = canSendDmMessage({
53
+ sending: submitting,
54
+ uploadsPending: attachments.some(isAttachmentProcessing),
55
+ text: message,
56
+ attachments,
38
57
  });
39
58
 
59
+ const openImagePicker = useCallback(async () => {
60
+ const hasPermission = await checkMediaPermissions(t, 'photo');
61
+ if (hasPermission) imagePickerRef.current?.present();
62
+ }, [t]);
63
+
64
+ const addAttachments = useCallback(
65
+ (images: MediaAttachment[]) => {
66
+ setAttachments((current) =>
67
+ [...current, ...images].slice(0, DM_MAX_ATTACHMENTS)
68
+ );
69
+ },
70
+ [setAttachments]
71
+ );
72
+
40
73
  useEffect(() => {
41
74
  if (contnt) setMessage(contnt);
42
75
  }, [contnt, setMessage]);
@@ -65,6 +98,21 @@ export const DraftMessage = ({ navigation }: DraftMessageProps) => {
65
98
  </ScrollView>
66
99
 
67
100
  <ThemedView className="p-2 border-t border-border bg-background">
101
+ {attachments.length > 0 ? (
102
+ <ComposeAttachments
103
+ attachments={attachments}
104
+ removeAttachment={(index) =>
105
+ setAttachments((current) =>
106
+ current.filter((_, i) => i !== index)
107
+ )
108
+ }
109
+ updateAttachment={(index, attachment) =>
110
+ setAttachments((current) =>
111
+ current.map((item, i) => (i === index ? attachment : item))
112
+ )
113
+ }
114
+ />
115
+ ) : null}
68
116
  <OpenpeepsMarkdownInput
69
117
  rows={5}
70
118
  value={message}
@@ -74,18 +122,22 @@ export const DraftMessage = ({ navigation }: DraftMessageProps) => {
74
122
  defaultValue: 'Write a message…',
75
123
  })}
76
124
  />
77
- <View className="flex-row justify-end">
125
+ <View className="flex-row items-center justify-between">
126
+ <Button
127
+ size="icon"
128
+ variant="ghost"
129
+ accessibilityLabel={t('posts.form.addImage')}
130
+ onPress={() => void openImagePicker()}
131
+ disabled={submitting || attachments.length >= DM_MAX_ATTACHMENTS}
132
+ testID="conversation-add-image"
133
+ >
134
+ <ImageIcon size={20} className="text-foreground" />
135
+ </Button>
78
136
  <TouchableOpacity
79
137
  onPress={() => void send()}
80
- disabled={
81
- !message.trim() ||
82
- submitting ||
83
- message.length > maxContentLength
84
- }
138
+ disabled={!canSend}
85
139
  className={`p-2 rounded-full ${
86
- message.trim() && message.length <= maxContentLength
87
- ? 'bg-primary'
88
- : 'bg-surface'
140
+ canSend ? 'bg-primary' : 'bg-surface'
89
141
  }`}
90
142
  >
91
143
  {submitting ? (
@@ -97,6 +149,11 @@ export const DraftMessage = ({ navigation }: DraftMessageProps) => {
97
149
  </View>
98
150
  </ThemedView>
99
151
  </KeyboardAvoidingView>
152
+ <ImagePickerSheet
153
+ ref={imagePickerRef}
154
+ usage="post-image"
155
+ onSelect={addAttachments}
156
+ />
100
157
  </ThemedView>
101
158
  );
102
159
  };
@@ -1,10 +1,13 @@
1
1
  import React, { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { BottomSheetModal } from '@gorhom/bottom-sheet';
2
3
  import { MainScreenProps } from '../../components/navigation/types/index';
3
4
  import {
4
5
  adjustUnseenCounts,
5
6
  apiErrorMessage,
7
+ canSendDmMessage,
6
8
  useOpenpeeps,
7
9
  usePostViewFlush,
10
+ DM_MAX_ATTACHMENTS,
8
11
  } from '@openpeepshq/react';
9
12
  import { useTranslation } from 'react-i18next';
10
13
  import { useSetPageHeader } from '../../components/layout';
@@ -18,9 +21,16 @@ import {
18
21
  ActivityIndicator,
19
22
  } from 'react-native';
20
23
  import Toast from 'react-native-toast-message';
21
- import { InfoIcon, SearchIcon } from '../../components/icons/index';
22
- import { MediaAttachmentData, type PublicPost } from '@openpeepshq/common';
24
+ import { ImageIcon, InfoIcon, SearchIcon } from '../../components/icons/index';
25
+ import {
26
+ MediaAttachment,
27
+ MediaAttachmentData,
28
+ type PublicPost,
29
+ } from '@openpeepshq/common';
30
+ import { ImagePickerSheet } from '../../components/custom/index';
23
31
  import { ComposeAttachments } from '../../components/post/post-form/ComposeAttachments';
32
+ import { checkMediaPermissions } from '../../lib/media-permissions';
33
+ import { isAttachmentProcessing } from '../../lib/post';
24
34
  import { OpenpeepsMarkdownInput } from '../../components/post/post-form/OpenpeepsMarkdownInput';
25
35
  import { maxContentLength } from '../../lib/utils';
26
36
  import { DropdownMenu } from '../../components/ui/dropdown-menu';
@@ -76,10 +86,15 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
76
86
  const [shownMessages, setShownMessages] = useState<PublicPost[]>([]);
77
87
  const [shownFor, setShownFor] = useState(id);
78
88
  const [searchOpen, setSearchOpen] = useState(false);
89
+ const [isSending, setIsSending] = useState(false);
90
+ const [attachments, setAttachments] = useState<MediaAttachmentData[]>([]);
91
+ const [content, setContent] = useState('');
79
92
  if (shownFor !== id) {
80
93
  setShownFor(id);
81
94
  setShownMessages([]);
82
95
  setSearchOpen(false);
96
+ setContent('');
97
+ setAttachments([]);
83
98
  }
84
99
  useEffect(() => {
85
100
  if (conversationQuery.data) setShownMessages(conversationQuery.data);
@@ -88,10 +103,8 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
88
103
  const isLoading = conversationQuery.isLoading && messages.length === 0;
89
104
  const markPostsSeen = openpeepsApi.markPostsSeenAction();
90
105
  const flushPostViews = usePostViewFlush();
91
- const [isSending, setIsSending] = useState(false);
92
- const [attachments, setAttachments] = useState<MediaAttachmentData[]>([]);
93
- const [content, setContent] = useState('');
94
106
  const scrollViewRef = useRef<ScrollView>(null);
107
+ const imagePickerRef = useRef<BottomSheetModal>(null);
95
108
  const messageOffsets = useRef<Record<string, number>>({});
96
109
  const scrolledToMessageRef = useRef<string | null>(null);
97
110
  const [participantsOpen, setParticipantsOpen] = useState(false);
@@ -115,10 +128,26 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
115
128
  setAttachments([]);
116
129
  }, []);
117
130
 
131
+ const canSend = canSendDmMessage({
132
+ sending: isSending,
133
+ uploadsPending: attachments.some(isAttachmentProcessing),
134
+ text: content,
135
+ attachments,
136
+ });
137
+
138
+ const openImagePicker = useCallback(async () => {
139
+ const hasPermission = await checkMediaPermissions(t, 'photo');
140
+ if (hasPermission) imagePickerRef.current?.present();
141
+ }, [t]);
142
+
143
+ const addAttachments = useCallback((images: MediaAttachment[]) => {
144
+ setAttachments((current) =>
145
+ [...current, ...images].slice(0, DM_MAX_ATTACHMENTS)
146
+ );
147
+ }, []);
148
+
118
149
  const handleSendMessage = async () => {
119
- if (!content.trim() || content.length > maxContentLength) {
120
- return;
121
- }
150
+ if (!canSend) return;
122
151
 
123
152
  try {
124
153
  setIsSending(true);
@@ -128,7 +157,8 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
128
157
  type: 'note',
129
158
  data: {
130
159
  type: 'note',
131
- content: content,
160
+ content: content.trim(),
161
+ attachments: attachments.length ? attachments : undefined,
132
162
  },
133
163
  });
134
164
  resetForm();
@@ -344,15 +374,23 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
344
374
  defaultValue: 'Write a message…',
345
375
  })}
346
376
  />
347
- <View className="flex-row justify-end">
377
+ <View className="flex-row items-center justify-between">
348
378
  <Button
349
- variant="default"
350
- onPress={handleSendMessage}
379
+ size="icon"
380
+ variant="ghost"
381
+ accessibilityLabel={t('posts.form.addImage')}
382
+ onPress={() => void openImagePicker()}
351
383
  disabled={
352
- isSending ||
353
- !content.trim() ||
354
- content.length > maxContentLength
384
+ isSending || attachments.length >= DM_MAX_ATTACHMENTS
355
385
  }
386
+ testID="conversation-add-image"
387
+ >
388
+ <ImageIcon size={20} className="text-foreground" />
389
+ </Button>
390
+ <Button
391
+ variant="default"
392
+ onPress={handleSendMessage}
393
+ disabled={!canSend}
356
394
  >
357
395
  {isSending ? (
358
396
  <View className="flex-row items-center">
@@ -380,6 +418,11 @@ export const ConversationShow = ({ route, navigation }: ConversationProps) => {
380
418
  />
381
419
  ) : null}
382
420
  </View>
421
+ <ImagePickerSheet
422
+ ref={imagePickerRef}
423
+ usage="post-image"
424
+ onSelect={addAttachments}
425
+ />
383
426
  </ThemedView>
384
427
  );
385
428
  };