Skip to content

Commit

Permalink
fix: add support for svg uris without viewbox (#10247)
Browse files Browse the repository at this point in the history
## **Description**

We have ran into some SVG rendering issues with SVG URIs. This is due to
some SVGs do not contain a view-box, thus can be much larger or smaller
than the container it is trying to fit in.

For example:
- [This
SVG](https://raw.githubusercontent.com/MetaMask/contract-metadata/master/images/usdt.svg)
does not have a viewbox, and does not "render correctly"
- [This
SVG](https://token.api.cx.metamask.io/assets/nativeCurrencyLogos/ethereum.svg)
does have a viewbox and can be rendered correctly.

<details><summary>See Example Screenshot</summary>

![Screenshot 2024-07-04 at 02 36
32](https://github.com/MetaMask/metamask-mobile/assets/17534261/71b29017-bb0c-43a0-8b36-eba93489c643)

</details> 

This adds an effect to use the SVG width/height for setting a view box
if not set in the SVG.

## **Related issues**

Known issue and temporary fix in `react-native-svg`:

software-mansion/react-native-svg#1202 (comment)

## **Manual testing steps**


## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

<details><summary>Before</summary>

![Screenshot 2024-07-04 at 02 36
32](https://github.com/MetaMask/metamask-mobile/assets/17534261/1a716d94-cd63-4aad-a995-4075cc14346c)

</details> 

### **After**

<details><summary>After</summary>

![Screenshot 2024-07-04 at 12 32
35](https://github.com/MetaMask/metamask-mobile/assets/17534261/831cb931-01fc-4ffe-a4cc-1ef122c2f525)

</details> 

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [x] I’ve followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I’ve included tests if applicable
- [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.
  • Loading branch information
Prithpal-Sooriya authored Jul 4, 2024
1 parent 3b5945c commit 9b695e4
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 7 deletions.
24 changes: 17 additions & 7 deletions app/components/Base/RemoteImage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import ComponentErrorBoundary from '../../UI/ComponentErrorBoundary';
import useIpfsGateway from '../../hooks/useIpfsGateway';
import { getFormattedIpfsUrl } from '@metamask/assets-controllers';
import Identicon from '../../UI/Identicon';
import useSvgUriViewBox from '../../hooks/useSvgUriViewBox';

const createStyles = () =>
StyleSheet.create({
Expand Down Expand Up @@ -40,16 +41,19 @@ const RemoteImage = (props) => {

const onError = ({ nativeEvent: { error } }) => setError(error);

const isSVG =
source &&
source.uri &&
source.uri.match('.svg') &&
(isImageUrl || resolvedIpfsUrl);

const viewbox = useSvgUriViewBox(uri, isSVG);

if (error && props.address) {
return <Identicon address={props.address} customStyle={props.style} />;
}

if (
source &&
source.uri &&
source.uri.match('.svg') &&
(isImageUrl || resolvedIpfsUrl)
) {
if (isSVG) {
const style = props.style || {};
if (source.__packager_asset && typeof style !== 'number') {
if (!style.width) {
Expand All @@ -66,7 +70,13 @@ const RemoteImage = (props) => {
componentLabel="RemoteImage-SVG"
>
<View style={{ ...style, ...styles.svgContainer }}>
<SvgUri {...props} uri={uri} width={'100%'} height={'100%'} />
<SvgUri
{...props}
uri={uri}
width={'100%'}
height={'100%'}
viewBox={viewbox}
/>
</View>
</ComponentErrorBoundary>
);
Expand Down
42 changes: 42 additions & 0 deletions app/components/hooks/useSvgUriViewBox.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { renderHook, waitFor } from '@testing-library/react-native';
import useSvgUriViewBox from './useSvgUriViewBox';

describe('useSvgUriViewBox()', () => {
const MOCK_SVG_WITH_VIEWBOX = `<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60" fill="none"></svg>`;
const MOCK_SVG_WITHOUT_VIEWBOX = `<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" fill="none"></svg>`;

function arrangeMocks() {
const mockResponseTextFn = jest
.fn()
.mockResolvedValue(MOCK_SVG_WITHOUT_VIEWBOX);
jest
.spyOn(global, 'fetch')
.mockResolvedValue({ text: mockResponseTextFn } as unknown as Response);

return { mockText: mockResponseTextFn };
}

it('should return view-box if svg if missing a view-box', async () => {
const { mockText } = arrangeMocks();
mockText.mockResolvedValueOnce(MOCK_SVG_WITHOUT_VIEWBOX);

const hook = renderHook(() => useSvgUriViewBox('URI', true));
await waitFor(() => expect(hook.result.current).toBeDefined());
});

it('should return view-box if svg already has view-box', async () => {
const { mockText } = arrangeMocks();
mockText.mockResolvedValueOnce(MOCK_SVG_WITH_VIEWBOX);

const hook = renderHook(() => useSvgUriViewBox('URI', true));
await waitFor(() => expect(hook.result.current).toBeDefined());
});

it('should not make async calls if image is not an svg', async () => {
const mocks = arrangeMocks();
const hook = renderHook(() => useSvgUriViewBox('URI', false));

await waitFor(() => expect(hook.result.current).toBeUndefined());
expect(mocks.mockText).not.toHaveBeenCalled();
});
});
49 changes: 49 additions & 0 deletions app/components/hooks/useSvgUriViewBox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useEffect, useState } from 'react';

/**
* Support svg images urls that do not have a view box
* See: https://github.com/software-mansion/react-native-svg/issues/1202#issuecomment-1891110599
*
* This will return the default SVG ViewBox from an SVG URI
* @param uri - uri to fetch
* @param isSVG - check to see if the uri is an svg
* @returns viewbox string
*/
export default function useSvgUriViewBox(
uri: string,
isSVG: boolean,
): string | undefined {
const [viewBox, setViewBox] = useState<string | undefined>(undefined);

useEffect(() => {
if (!isSVG) {
return;
}

fetch(uri)
.then((response) => response.text())
.then((svgContent) => {
const widthMatch = svgContent.match(/width="([^"]+)"/);
const heightMatch = svgContent.match(/height="([^"]+)"/);
const viewBoxMatch = svgContent.match(/viewBox="([^"]+)"/);

if (viewBoxMatch?.[1]) {
setViewBox(viewBoxMatch[1]);
return;
}

if (widthMatch?.[1] && heightMatch?.[1]) {
const width = widthMatch[1];
const height = heightMatch[1];
setViewBox(`0 0 ${width} ${height}`);
}
})
.catch((error) => console.error('Error fetching SVG:', error));
}, [isSVG, uri]);

if (!viewBox) {
return undefined;
}

return viewBox;
}

0 comments on commit 9b695e4

Please sign in to comment.