@openpeepshq/rn-components 0.10.0 → 0.10.2

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,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}