Skip to content

**feat**: provide svg props in onload #2540

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,15 @@ If remote SVG file contains CSS in `<style>` element, use `SvgCssUri`:
import * as React from 'react';
import { ActivityIndicator, View, StyleSheet } from 'react-native';
import { SvgCssUri } from 'react-native-svg/css';
import type { SvgProps } from 'react-native-svg';
export default function TestComponent() {
const [loading, setLoading] = React.useState(true);
const onError = (e: Error) => {
console.log(e.message);
setLoading(false);
};
const onLoad = () => {
console.log('Svg loaded!');
const onLoad = (svgProps: SvgProps) => {
console.log('Svg loaded!', svgProps);
setLoading(false);
};
return (
Expand Down
181 changes: 181 additions & 0 deletions apps/common/test/SvgUriOnLoad.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import React, {useState} from 'react';
import {View, Text} from 'react-native';
import {SvgProps, SvgUri} from '../../../src';
import {SvgCssUri} from 'react-native-svg/css';

const svgDataUri =
'data:image/svg+xml;base64,' +
btoa(`
<svg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg" fill="pink">
<ellipse cx="30" cy="30" rx="30" ry="15" fill="yellow" />
</svg>
`);

const cssSvgDataUri =
'data:image/svg+xml;base64,' +
btoa(`
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<style>
.small { font: italic 13px sans-serif; }
</style>
<rect x="0" y="0" width="100" height="100" fill="yellow" />
<text x="20" y="35" class="small">CSS Styled</text>
</svg>
`);

const calculateWidth = (svgProps: SvgProps, desiredHeight: number) => {
let originalHeight = svgProps.height;
let originalWidth = svgProps.width;
if (originalWidth && originalHeight) {
return (Number(originalWidth) / Number(originalHeight)) * desiredHeight;
}
};

const ExampleWithSvgUri = () => {
const [width, setWidth] = useState(0);
const height = 12;

const handleLoad = (svgProps: SvgProps) => {
const calculatedWidth = calculateWidth(svgProps, height);
if (calculatedWidth) {
setWidth(calculatedWidth);
}
};
return (
<View style={{flex: 1}}>
<Text style={{fontSize: 24, color: '#fff'}}>SvgUri component</Text>

<Text style={{marginTop: 10, color: '#fff'}}>Original Size ✅</Text>
<SvgUri style={{backgroundColor: 'blue'}} uri={svgDataUri} />

<Text style={{marginTop: 10, color: '#fff'}}>
Set different height ❌
</Text>
<SvgUri
style={{backgroundColor: 'red'}}
uri={svgDataUri}
height={height}
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio Meet ❌
</Text>
<SvgUri
style={{backgroundColor: 'red'}}
uri={svgDataUri}
height={height}
preserveAspectRatio="xMinYMid meet"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio Slice ❌
</Text>
<SvgUri
style={{backgroundColor: 'red'}}
uri={svgDataUri}
height={height}
preserveAspectRatio="xMinYMid slice"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio None ❌
</Text>
<SvgUri
style={{backgroundColor: 'red'}}
uri={svgDataUri}
height={height}
preserveAspectRatio="none"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Auto calculate width ✅
</Text>
<SvgUri
style={{backgroundColor: 'green'}}
uri={svgDataUri}
height={height}
width={width}
onLoad={handleLoad}
/>
</View>
);
};

const ExampleWithSvgCssUri = () => {
const [width, setWidth] = useState(0);
const height = 25;
const handleLoad = (svgProps: SvgProps) => {
const calculatedWidth = calculateWidth(svgProps, height);
if (calculatedWidth) {
setWidth(calculatedWidth);
}
};

return (
<View style={{flex: 1}}>
<Text style={{fontSize: 24, color: '#fff'}}>SvgCssUri component</Text>

<Text style={{marginTop: 10, color: '#fff'}}>Original Size ✅</Text>
<SvgCssUri style={{backgroundColor: 'blue'}} uri={cssSvgDataUri} />

<Text style={{marginTop: 10, color: '#fff'}}>
Set different height ❌
</Text>
<SvgCssUri
style={{backgroundColor: 'red'}}
height={height}
uri={cssSvgDataUri}
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio Meet ❌
</Text>
<SvgCssUri
style={{backgroundColor: 'red'}}
height={height}
uri={cssSvgDataUri}
preserveAspectRatio="xMinYMid meet"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio Slice ❌
</Text>
<SvgCssUri
style={{backgroundColor: 'red'}}
height={height}
uri={cssSvgDataUri}
preserveAspectRatio="xMinYMid slice"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Preserve Aspect Ratio None ❌
</Text>
<SvgCssUri
style={{backgroundColor: 'red'}}
height={height}
uri={cssSvgDataUri}
preserveAspectRatio="none"
/>

<Text style={{marginTop: 10, color: '#fff'}}>
Auto calculate width ✅
</Text>
<SvgCssUri
style={{backgroundColor: 'green'}}
height={height}
uri={cssSvgDataUri}
width={width}
onLoad={handleLoad}
/>
</View>
);
};

export default () => {
return (
<View style={{flex: 1, padding: 10, flexDirection: 'row'}}>
<ExampleWithSvgUri />
<ExampleWithSvgCssUri />
</View>
);
};
1 change: 1 addition & 0 deletions apps/common/test/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import Test2417 from './Test2417';
import Test2455 from './Test2455';
import Test2471 from './Test2471';
import Test2520 from './Test2520';
import Test2540 from './SvgUriOnLoad';
import Test2670 from './Test2670';

export default function App() {
Expand Down
35 changes: 24 additions & 11 deletions src/css/css.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -766,17 +766,29 @@ export const inlineStyles: Middleware = function inlineStyles(
};

export function SvgCss(props: XmlProps) {
const { xml, override, fallback, onError = err } = props;
try {
const ast = useMemo<JsxAST | null>(
() => (xml !== null ? parse(xml, inlineStyles) : null),
[xml]
);
return <SvgAst ast={ast} override={override || props} />;
} catch (error) {
onError(error);
const { xml, override, fallback, onError = err, onLoad } = props;

const [ast, error] = useMemo<[JsxAST | null, unknown]>(() => {
try {
const parsed = xml !== null ? parse(xml, inlineStyles) : null;
return [parsed, null];
} catch (exc) {
return [null, exc];
}
}, [xml]);

useEffect(() => {
if (!error && ast?.props) {
onLoad?.(ast.props);
} else if (error) {
onError(error as Error);
}
}, [ast, error, onLoad, onError]);

if (error) {
return fallback ?? null;
}
return <SvgAst ast={ast} override={override || props} />;
}

export function SvgCssUri(props: UriProps) {
Expand All @@ -788,7 +800,6 @@ export function SvgCssUri(props: UriProps) {
? fetchText(uri)
.then((data) => {
setXml(data);
onLoad?.();
})
.catch((e) => {
onError(e);
Expand All @@ -799,7 +810,9 @@ export function SvgCssUri(props: UriProps) {
if (isError) {
return fallback ?? null;
}
return <SvgCss xml={xml} override={props} fallback={fallback} />;
return (
<SvgCss xml={xml} override={props} fallback={fallback} onLoad={onLoad} />
);
}

// Extending Component is required for Animated support.
Expand Down
36 changes: 24 additions & 12 deletions src/xml.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface JsxAST extends AST {
export type AdditionalProps = {
onError?: (error: Error) => void;
override?: object;
onLoad?: () => void;
onLoad?: (svgProps: SvgProps) => void;
fallback?: JSX.Element;
};

Expand Down Expand Up @@ -65,18 +65,29 @@ export function SvgAst({ ast, override }: AstProps) {
const err = console.error.bind(console);

export function SvgXml(props: XmlProps) {
const { onError = err, xml, override, fallback } = props;
const { onError = err, xml, override, fallback, onLoad } = props;

try {
const ast = useMemo<JsxAST | null>(
() => (xml !== null ? parse(xml) : null),
[xml]
);
return <SvgAst ast={ast} override={override || props} />;
} catch (error) {
onError(error);
const [ast, error] = useMemo<[JsxAST | null, unknown]>(() => {
try {
const parsed = xml !== null ? parse(xml) : null;
return [parsed, null];
} catch (exc) {
return [null, exc];
}
}, [xml]);

useEffect(() => {
if (!error && ast?.props) {
onLoad?.(ast.props);
} else if (error) {
onError(error as Error);
}
}, [ast, error, onError, onLoad]);

if (error) {
return fallback ?? null;
}
return <SvgAst ast={ast} override={override || props} />;
}

export function SvgUri(props: UriProps) {
Expand All @@ -89,7 +100,6 @@ export function SvgUri(props: UriProps) {
.then((data) => {
setXml(data);
isError && setIsError(false);
onLoad?.();
})
.catch((e) => {
onError(e);
Expand All @@ -101,7 +111,9 @@ export function SvgUri(props: UriProps) {
if (isError) {
return fallback ?? null;
}
return <SvgXml xml={xml} override={props} fallback={fallback} />;
return (
<SvgXml xml={xml} override={props} fallback={fallback} onLoad={onLoad} />
);
}

// Extending Component is required for Animated support.
Expand Down