@momo-kits/foundation 0.169.16-beta.2 → 0.169.16-beta.20

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/Icon/index.tsx CHANGED
@@ -10,6 +10,7 @@ import { Colors } from '../Consts';
10
10
  /**
11
11
  * Tinted icon from the bundled icon map (unknown names fall back to
12
12
  * `ic_warning`) or from a URL. `color={null}` keeps the image's own colors.
13
+ * URLs never switch to WebP, matching the Compose/SwiftUI Icon.
13
14
  */
14
15
  const Icon: React.FC<IconProps> = ({
15
16
  source = 'ic_back',
@@ -38,6 +39,7 @@ const Icon: React.FC<IconProps> = ({
38
39
  <Image
39
40
  {...props}
40
41
  loading={false}
42
+ webp={false}
41
43
  source={getIconSource()}
42
44
  style={[
43
45
  style,
@@ -0,0 +1,90 @@
1
+ import { WEBP_ACCEPT, getWebpSource, isWebpCandidate } from '../utils';
2
+
3
+ const PNG = 'https://static.momocdn.net/app/img/kits/trustBanner/pci_dss.png';
4
+ const IMG_HOST_PNG = 'https://img.mservice.com.vn/app/img/kits/01.MoMo.png';
5
+
6
+ describe('isWebpCandidate', () => {
7
+ it.each([
8
+ PNG,
9
+ IMG_HOST_PNG,
10
+ 'http://static.momocdn.net/a.jpg',
11
+ 'https://STATIC.MOMOCDN.NET/a.jpg',
12
+ 'https://static.momocdn.net:443/a.jpg',
13
+ 'https://static.momocdn.net',
14
+ `${PNG}?w=100&h=50`,
15
+ `${PNG}#top`,
16
+ `${PNG}?imageformat=jpg`,
17
+ 'https://static.momocdn.net/format=jpg/a.png',
18
+ ])('accepts %s', uri => {
19
+ expect(isWebpCandidate(uri)).toBe(true);
20
+ });
21
+
22
+ it.each([
23
+ 'https://static.momocdn.net/a.webp',
24
+ 'https://static.momocdn.net/a.GIF',
25
+ 'https://img.mservice.com.vn/a.Svg',
26
+ 'https://static.momocdn.net/a.webp?v=2',
27
+ 'https://static.momocdn.net/a.gif#x',
28
+ `${PNG}?format=jpg`,
29
+ `${PNG}?w=1&format=png`,
30
+ `${PNG}?format`,
31
+ 'https://example.com/a.png',
32
+ 'https://cdn.static.momocdn.net/a.png',
33
+ 'https://static.momocdn.net.evil.com/a.png',
34
+ 'file:///data/a.png',
35
+ 'static.momocdn.net/a.png',
36
+ 'data:image/png;base64,AAAA',
37
+ '',
38
+ ])('rejects %s', uri => {
39
+ expect(isWebpCandidate(uri)).toBe(false);
40
+ });
41
+ });
42
+
43
+ describe('getWebpSource', () => {
44
+ it('adds the WebP Accept header and keeps the uri', () => {
45
+ expect(getWebpSource({ uri: IMG_HOST_PNG })).toEqual({
46
+ uri: IMG_HOST_PNG,
47
+ headers: { Accept: WEBP_ACCEPT },
48
+ });
49
+ });
50
+
51
+ it('keeps the query, fragment and other source fields', () => {
52
+ const source = { uri: `${PNG}?w=1#top`, priority: 'high', cache: 'web' };
53
+ expect(getWebpSource(source)).toEqual({
54
+ ...source,
55
+ headers: { Accept: WEBP_ACCEPT },
56
+ });
57
+ });
58
+
59
+ it('keeps the existing headers', () => {
60
+ const source = { uri: PNG, headers: { Authorization: 'token' } };
61
+ expect(getWebpSource(source)).toEqual({
62
+ uri: PNG,
63
+ headers: { Authorization: 'token', Accept: WEBP_ACCEPT },
64
+ });
65
+ });
66
+
67
+ it('does not mutate the given source', () => {
68
+ const source = { uri: PNG, headers: { Authorization: 'token' } };
69
+ getWebpSource(source);
70
+ expect(source).toEqual({ uri: PNG, headers: { Authorization: 'token' } });
71
+ });
72
+
73
+ it.each(['Accept', 'accept', 'ACCEPT'])(
74
+ 'leaves a source with its own %s header alone',
75
+ name => {
76
+ const source = { uri: PNG, headers: { [name]: 'image/png' } };
77
+ expect(getWebpSource(source)).toBeUndefined();
78
+ },
79
+ );
80
+
81
+ it.each([
82
+ {},
83
+ { uri: 'https://static.momocdn.net/a.gif' },
84
+ { uri: `${PNG}?format=jpg` },
85
+ { uri: 'https://example.com/a.png' },
86
+ { uri: 'file:///data/a.png' },
87
+ ])('leaves a non-candidate source alone: %p', source => {
88
+ expect(getWebpSource(source)).toBeUndefined();
89
+ });
90
+ });
package/Image/index.tsx CHANGED
@@ -12,6 +12,7 @@ import { Skeleton } from '../Skeleton';
12
12
  import { Icon } from '../Icon';
13
13
  import { Styles } from '../Consts';
14
14
  import { ImageProps } from './types';
15
+ import { useWebpSource } from './useWebpSource';
15
16
 
16
17
  type Status = 'success' | 'loading' | 'error';
17
18
 
@@ -26,12 +27,13 @@ export const getImageName = (source: any): string => {
26
27
 
27
28
  /**
28
29
  * FastImage that shows a skeleton while loading (if `loading`) or inside a
29
- * loading `SkeletonProvider`, and a fail icon on error.
30
+ * loading `SkeletonProvider`, and a fail icon on error. CDN images ask for WebP.
30
31
  */
31
32
  const Image: React.FC<ImageProps> = ({
32
33
  style,
33
34
  source,
34
35
  loading = true,
36
+ webp = true,
35
37
  children,
36
38
  onProgress,
37
39
  onLoadStart,
@@ -45,9 +47,13 @@ const Image: React.FC<ImageProps> = ({
45
47
  const context = useContext<any>(MiniAppContext);
46
48
  const skeleton = useContext(SkeletonContext);
47
49
  const hasErrorRef = useRef(false);
50
+ const isWebpFailedRef = useRef(false);
48
51
  const [status, setStatus] = useState<Status>('success');
49
52
 
50
53
  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;
54
+ const dsConfig = context?.designSystemConfig?.config;
55
+ const isWebpConfigOn = dsConfig?.imageWebp !== false;
56
+ const webpSource = useWebpSource(source, webp && isWebpConfigOn);
51
57
 
52
58
  const imageName = getImageName(source);
53
59
  let accessibilityLabel: any = `img|${imageName}`;
@@ -85,7 +91,7 @@ const Image: React.FC<ImageProps> = ({
85
91
  <FastImage
86
92
  {...rest}
87
93
  {...{ accessibilityLabel: rest.accessibilityLabel ?? accessibilityLabel }}
88
- source={source}
94
+ source={webpSource.source}
89
95
  style={[
90
96
  styles.container,
91
97
  style,
@@ -100,6 +106,7 @@ const Image: React.FC<ImageProps> = ({
100
106
  }}
101
107
  onLoadStart={() => {
102
108
  hasErrorRef.current = false;
109
+ isWebpFailedRef.current = false;
103
110
  onLoadStart?.();
104
111
  }}
105
112
  onLoad={event => {
@@ -107,6 +114,11 @@ const Image: React.FC<ImageProps> = ({
107
114
  onLoad?.(event);
108
115
  }}
109
116
  onLoadEnd={() => {
117
+ // The failed WebP attempt stays invisible: the plain source loads next.
118
+ if (isWebpFailedRef.current) {
119
+ isWebpFailedRef.current = false;
120
+ return;
121
+ }
110
122
  let current: Status = 'success';
111
123
  if (hasErrorRef.current) {
112
124
  current = 'error';
@@ -115,6 +127,11 @@ const Image: React.FC<ImageProps> = ({
115
127
  onLoadEnd?.();
116
128
  }}
117
129
  onError={() => {
130
+ if (webpSource.isWebp) {
131
+ isWebpFailedRef.current = true;
132
+ webpSource.fallBack();
133
+ return;
134
+ }
118
135
  hasErrorRef.current = true;
119
136
  onError?.();
120
137
  }}
package/Image/types.ts CHANGED
@@ -4,4 +4,10 @@ export interface ImageProps extends FastImageProps {
4
4
  loading?: boolean;
5
5
  accessibilityLabel?: any;
6
6
  params?: any;
7
+ /**
8
+ * Asks the MoMo CDN (`img.mservice.com.vn`, `static.momocdn.net`) for WebP via
9
+ * the Accept header, retrying the plain source once if that fails. Default
10
+ * `true`; the `imageWebp: false` design system config turns it off everywhere.
11
+ */
12
+ webp?: boolean;
7
13
  }
@@ -0,0 +1,52 @@
1
+ import { useCallback, useMemo, useState } from 'react';
2
+ import { type Source } from 'react-native-fast-image';
3
+ import { type ImageProps } from './types';
4
+ import { getWebpSource } from './utils';
5
+
6
+ type ImageSource = ImageProps['source'];
7
+
8
+ /** JSON of the WebP variant of a `{ uri }` source; undefined if not a candidate. */
9
+ const getWebpKey = (source: ImageSource): string | undefined => {
10
+ if (typeof source !== 'object' || !source) {
11
+ return undefined;
12
+ }
13
+ const webpSource = getWebpSource(source);
14
+ if (!webpSource) {
15
+ return undefined;
16
+ }
17
+ return JSON.stringify(webpSource);
18
+ };
19
+
20
+ /**
21
+ * Asks the MoMo CDN for WebP (Accept header) until that request fails once,
22
+ * then loads the caller's source as is. A new uri or headers try WebP again.
23
+ */
24
+ const useWebpSource = (source: ImageSource, isEnabled: boolean) => {
25
+ const [failedWebpKey, setFailedWebpKey] = useState<string>();
26
+
27
+ let webpKey: string | undefined;
28
+ if (isEnabled) {
29
+ webpKey = getWebpKey(source);
30
+ }
31
+ const isWebp = webpKey !== undefined && webpKey !== failedWebpKey;
32
+
33
+ // Keyed by JSON so an inline `{ uri }` doesn't hand FastImage a new source each render.
34
+ const webpSource = useMemo((): Source | undefined => {
35
+ if (webpKey === undefined) {
36
+ return undefined;
37
+ }
38
+ return JSON.parse(webpKey);
39
+ }, [webpKey]);
40
+
41
+ const fallBack = useCallback(() => {
42
+ setFailedWebpKey(webpKey);
43
+ }, [webpKey]);
44
+
45
+ let loadSource = source;
46
+ if (isWebp && webpSource) {
47
+ loadSource = webpSource;
48
+ }
49
+ return { source: loadSource, isWebp, fallBack };
50
+ };
51
+
52
+ export { useWebpSource };
package/Image/utils.ts ADDED
@@ -0,0 +1,61 @@
1
+ const WEBP_HOSTS = ['img.mservice.com.vn', 'static.momocdn.net'];
2
+ // Image loaders send `image/*,*/*`, which the CDN answers with the original format.
3
+ const WEBP_ACCEPT = 'image/webp,image/*,*/*;q=0.8';
4
+ const ACCEPT_HEADER = 'accept';
5
+ const FORMAT_PARAM = 'format';
6
+ const SKIPPED_EXTENSION = /\.(webp|gif|svg)$/i;
7
+ // Split by hand: RN's URL polyfill rewrites the string (adds `/`, moves `#`).
8
+ const HTTP_URL = /^https?:\/\/([^/?#:]+)(?::\d+)?([^?#]*)(\?[^#]*)?/i;
9
+
10
+ type UrlParts = { host: string; path: string; query: string };
11
+ type Headers = { [key: string]: string };
12
+ type HeaderSource = { uri?: string; headers?: Headers };
13
+
14
+ /** Host, path and `?query` of an http(s) URL; undefined otherwise. */
15
+ const parseHttpUrl = (uri: string): UrlParts | undefined => {
16
+ const match = HTTP_URL.exec(uri);
17
+ if (!match) {
18
+ return undefined;
19
+ }
20
+ const [, host, path, query = ''] = match;
21
+ return { host: host.toLowerCase(), path, query };
22
+ };
23
+
24
+ /** Whether the `?query` part already has a `format` param. */
25
+ const hasFormatParam = (query: string): boolean => {
26
+ const params = query.replace(/^\?/, '').split('&');
27
+ return params.some(param => param.split('=')[0] === FORMAT_PARAM);
28
+ };
29
+
30
+ /** Whether `headers` has an Accept header, in any letter case. */
31
+ const hasAcceptHeader = (headers?: Headers): boolean => {
32
+ const names = Object.keys(headers ?? {});
33
+ return names.some(name => name.toLowerCase() === ACCEPT_HEADER);
34
+ };
35
+
36
+ /**
37
+ * Whether the MoMo CDN can serve `uri` as WebP: http(s) on a CDN host, not
38
+ * already WebP/GIF/SVG and without a `format` param of its own.
39
+ */
40
+ const isWebpCandidate = (uri: string): boolean => {
41
+ const parts = parseHttpUrl(uri);
42
+ if (!parts || !WEBP_HOSTS.includes(parts.host)) {
43
+ return false;
44
+ }
45
+ return !SKIPPED_EXTENSION.test(parts.path) && !hasFormatParam(parts.query);
46
+ };
47
+
48
+ /**
49
+ * `source` plus an Accept header asking the CDN for WebP; undefined when the
50
+ * uri isn't a candidate or the caller already sets Accept. The uri is kept.
51
+ */
52
+ const getWebpSource = <T extends HeaderSource>(source: T): T | undefined => {
53
+ const { uri, headers } = source;
54
+ const isCandidate = typeof uri === 'string' && isWebpCandidate(uri);
55
+ if (!isCandidate || hasAcceptHeader(headers)) {
56
+ return undefined;
57
+ }
58
+ return { ...source, headers: { ...headers, Accept: WEBP_ACCEPT } };
59
+ };
60
+
61
+ export { WEBP_ACCEPT, isWebpCandidate, getWebpSource };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@momo-kits/foundation",
3
- "version": "0.169.16-beta.2",
3
+ "version": "0.169.16-beta.20",
4
4
  "description": "React Native Component Kits",
5
5
  "main": "index.ts",
6
6
  "scripts": {},