fix: bump packages, eslint, tsconfig, prettier and resolve all conflicts (#2114)

PR bumping packages, eslint, tsconfig, prettier and resolving all conflicts connected to it.
This commit is contained in:
Wojciech Lewicki
2023-08-07 17:44:58 +02:00
committed by GitHub
parent 3599c57e31
commit 416ccc8a86
64 changed files with 4762 additions and 4382 deletions

View File

@@ -1,13 +0,0 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

View File

@@ -1,12 +1,38 @@
module.exports = { module.exports = {
extends: '@react-native-community', root: true,
parserOptions: { parser: '@typescript-eslint/parser',
project: ["./tsconfig.json"], extends: [
'standard',
'plugin:@typescript-eslint/recommended',
'prettier',
'plugin:import/typescript',
],
plugins: ['react', 'react-native', 'import', '@typescript-eslint', 'react-hooks'],
env: {
'react-native/react-native': true,
},
settings: {
'import/resolver': {
'babel-module': {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
}, },
rules: { rules: {
'no-bitwise': 'off', 'import/no-unresolved': 'error',
'@typescript-eslint/consistent-type-exports': 'error', 'react/jsx-uses-vars': 'error',
'@typescript-eslint/consistent-type-imports': 'error', 'react/jsx-uses-react': 'error',
'@typescript-eslint/no-explicit-any': 'error', 'no-use-before-define': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-ignore': 'allow-with-description',
'ts-expect-error': 'allow-with-description',
},
],
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'@typescript-eslint/no-var-requires': 'warn',
eqeqeq: 'error',
'no-unreachable': 'error',
}, },
}; };

View File

@@ -1,13 +0,0 @@
[ignore]
.*/node_modules/resolve/test/resolver/malformed_package_json/package.json
[include]
[libs]
flow-typed
[lints]
[options]
[strict]

View File

@@ -15,10 +15,10 @@ jobs:
steps: steps:
- name: checkout - name: checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Use Node.js 16 - name: Use Node.js 18
uses: actions/setup-node@v2 uses: actions/setup-node@v2
with: with:
node-version: 16 node-version: 18
cache: 'yarn' cache: 'yarn'
cache-dependency-path: 'yarn.lock' cache-dependency-path: 'yarn.lock'
- name: Install node dependencies - name: Install node dependencies
@@ -30,4 +30,3 @@ jobs:
- name: Build Example App - name: Build Example App
working-directory: Example/ working-directory: Example/
run: yarn && yarn tsc run: yarn && yarn tsc

1
.gitignore vendored
View File

@@ -46,7 +46,6 @@ cn-doc.md
experimental/ experimental/
/lib/ /lib/
/flow-typed/
# VS Code # VS Code
.vscode/ .vscode/

View File

@@ -1,4 +0,0 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@@ -1,8 +1,8 @@
module.exports = { module.exports = {
arrowParens: 'avoid',
jsxBracketSameLine: true,
bracketSameLine: true, bracketSameLine: true,
bracketSpacing: false, printWidth: 80,
singleQuote: true, singleQuote: true,
trailingComma: 'all', trailingComma: 'es5',
tabWidth: 2,
arrowParens: 'always',
}; };

View File

@@ -1,8 +0,0 @@
sudo: false
language: node_js
node_js:
- '12'
script:
- npm test

View File

@@ -22,7 +22,6 @@ We use `typescript` for type checks, `eslint` with `prettier` for linting/format
- `yarn test`: Run all tests, except for e2e (see note below). - `yarn test`: Run all tests, except for e2e (see note below).
- `yarn lint`: Run `eslint` check. - `yarn lint`: Run `eslint` check.
- `yarn tsc`: Run `typescript` check. - `yarn tsc`: Run `typescript` check.
- `yarn flow`: Run `flow` type check.
- `yarn jest`: Run `jest` type check. - `yarn jest`: Run `jest` type check.
Currently e2e tests exist here: https://github.com/msand/react-native-svg-e2e/ Currently e2e tests exist here: https://github.com/msand/react-native-svg-e2e/

View File

@@ -484,7 +484,7 @@ PODS:
- React-jsi (= 0.72.1) - React-jsi (= 0.72.1)
- React-logger (= 0.72.1) - React-logger (= 0.72.1)
- React-perflogger (= 0.72.1) - React-perflogger (= 0.72.1)
- RNReanimated (3.3.0): - RNReanimated (3.4.2):
- DoubleConversion - DoubleConversion
- FBLazyVector - FBLazyVector
- glog - glog
@@ -513,7 +513,7 @@ PODS:
- React-RCTText - React-RCTText
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- Yoga - Yoga
- RNSVG (13.9.0): - RNSVG (13.10.0):
- React-Core - React-Core
- SocketRocket (0.6.1) - SocketRocket (0.6.1)
- Yoga (1.14.0) - Yoga (1.14.0)
@@ -740,8 +740,8 @@ SPEC CHECKSUMS:
React-runtimescheduler: 67707a955b9ecc628cc38bdc721fbc498910f0fd React-runtimescheduler: 67707a955b9ecc628cc38bdc721fbc498910f0fd
React-utils: 0a70ea97d4e2749f336b450c082905be1d389435 React-utils: 0a70ea97d4e2749f336b450c082905be1d389435
ReactCommon: e593d19c9e271a6da4d0bd7f13b28cfeae5d164b ReactCommon: e593d19c9e271a6da4d0bd7f13b28cfeae5d164b
RNReanimated: 9f7068e43b9358a46a688d94a5a3adb258139457 RNReanimated: 726395a2fa2f04cea340274ba57a4e659bc0d9c1
RNSVG: 53c661b76829783cdaf9b7a57258f3d3b4c28315 RNSVG: ee7e4ae98adade9ad8a12e7f9276504e71bd3ef7
SocketRocket: f32cd54efbe0f095c4d7594881e52619cfe80b17 SocketRocket: f32cd54efbe0f095c4d7594881e52619cfe80b17
Yoga: 65286bb6a07edce5e4fe8c90774da977ae8fc009 Yoga: 65286bb6a07edce5e4fe8c90774da977ae8fc009
YogaKit: f782866e155069a2cca2517aafea43200b01fd5a YogaKit: f782866e155069a2cca2517aafea43200b01fd5a

View File

@@ -17,13 +17,14 @@
"react": "18.2.0", "react": "18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-native": "0.72.1", "react-native": "0.72.1",
"react-native-reanimated": "^3.3.0", "react-native-reanimated": "^3.4.2",
"react-native-svg": "link:../", "react-native-svg": "link:../",
"react-native-web": "^0.18.12", "react-native-web": "^0.18.12",
"react-native-windows": "0.72.1" "react-native-windows": "0.72.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
"@babel/preset-env": "^7.20.0", "@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0", "@babel/runtime": "^7.20.0",
"@react-native/eslint-config": "^0.72.2", "@react-native/eslint-config": "^0.72.2",

File diff suppressed because it is too large Load Diff

View File

@@ -1057,7 +1057,7 @@ PODS:
- React-jsi (= 0.72.1) - React-jsi (= 0.72.1)
- React-logger (= 0.72.1) - React-logger (= 0.72.1)
- React-perflogger (= 0.72.1) - React-perflogger (= 0.72.1)
- RNReanimated (3.3.0): - RNReanimated (3.4.2):
- DoubleConversion - DoubleConversion
- FBLazyVector - FBLazyVector
- glog - glog
@@ -1087,23 +1087,39 @@ PODS:
- React-RCTText - React-RCTText
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- Yoga - Yoga
- RNSVG (13.9.0): - RNSVG (13.10.0):
- RCT-Folly - hermes-engine
- RCT-Folly (= 2021.07.22.00)
- RCTRequired - RCTRequired
- RCTTypeSafety - RCTTypeSafety
- React
- React-Codegen - React-Codegen
- React-Core
- React-debug
- React-Fabric
- React-graphics
- React-NativeModulesApple
- React-RCTFabric - React-RCTFabric
- React-utils
- ReactCommon/turbomodule/bridging
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- RNSVG/common (= 13.9.0) - RNSVG/common (= 13.10.0)
- RNSVG/common (13.9.0): - Yoga
- RCT-Folly - RNSVG/common (13.10.0):
- hermes-engine
- RCT-Folly (= 2021.07.22.00)
- RCTRequired - RCTRequired
- RCTTypeSafety - RCTTypeSafety
- React
- React-Codegen - React-Codegen
- React-Core
- React-debug
- React-Fabric
- React-graphics
- React-NativeModulesApple
- React-RCTFabric - React-RCTFabric
- React-utils
- ReactCommon/turbomodule/bridging
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- Yoga
- SocketRocket (0.6.1) - SocketRocket (0.6.1)
- Yoga (1.14.0) - Yoga (1.14.0)
- YogaKit (1.18.1): - YogaKit (1.18.1):
@@ -1342,8 +1358,8 @@ SPEC CHECKSUMS:
React-runtimescheduler: 67707a955b9ecc628cc38bdc721fbc498910f0fd React-runtimescheduler: 67707a955b9ecc628cc38bdc721fbc498910f0fd
React-utils: 0a70ea97d4e2749f336b450c082905be1d389435 React-utils: 0a70ea97d4e2749f336b450c082905be1d389435
ReactCommon: e593d19c9e271a6da4d0bd7f13b28cfeae5d164b ReactCommon: e593d19c9e271a6da4d0bd7f13b28cfeae5d164b
RNReanimated: 3ce2aec600ad2ef47a5927abf2742329d7a190e9 RNReanimated: 5008fe999d57038a1c5c1163044854d453f41b98
RNSVG: e6e82189bac969a139b3bb4740364a2e8aac31ec RNSVG: b677ab45318fca9f50dc361c1e3fd7c558dd0963
SocketRocket: f32cd54efbe0f095c4d7594881e52619cfe80b17 SocketRocket: f32cd54efbe0f095c4d7594881e52619cfe80b17
Yoga: 65286bb6a07edce5e4fe8c90774da977ae8fc009 Yoga: 65286bb6a07edce5e4fe8c90774da977ae8fc009
YogaKit: f782866e155069a2cca2517aafea43200b01fd5a YogaKit: f782866e155069a2cca2517aafea43200b01fd5a

View File

@@ -12,7 +12,7 @@
"dependencies": { "dependencies": {
"react": "18.2.0", "react": "18.2.0",
"react-native": "0.72.1", "react-native": "0.72.1",
"react-native-reanimated": "^3.3.0", "react-native-reanimated": "^3.4.2",
"react-native-svg": "link:../" "react-native-svg": "link:../"
}, },
"devDependencies": { "devDependencies": {

File diff suppressed because it is too large Load Diff

View File

@@ -11,33 +11,16 @@ Pod::Spec.new do |s|
s.license = package['license'] s.license = package['license']
s.homepage = package['homepage'] s.homepage = package['homepage']
s.authors = 'Horcrux Chen' s.authors = 'Horcrux Chen'
s.platforms = { :osx => "10.14", :ios => "9.0", :tvos => "9.2" }
s.source = { :git => 'https://github.com/react-native-community/react-native-svg.git', :tag => "v#{s.version}" } s.source = { :git => 'https://github.com/react-native-community/react-native-svg.git', :tag => "v#{s.version}" }
s.source_files = 'apple/**/*.{h,m,mm}'
if fabric_enabled s.ios.exclude_files = '**/*.macos.{h,m,mm}'
# folly_version must match the version used in React Native s.tvos.exclude_files = '**/*.macos.{h,m,mm}'
# See folly_version in react-native/React/FBReactNativeSpec/FBReactNativeSpec.podspec s.osx.exclude_files = '**/*.ios.{h,m,mm}'
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
s.pod_target_xcconfig = {
'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/boost" "$(PODS_ROOT)/boost-for-react-native" "$(PODS_ROOT)/RCT-Folly"',
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17",
}
s.platforms = { ios: '12.4', tvos: '11.0' }
s.compiler_flags = folly_compiler_flags + ' -DRCT_NEW_ARCH_ENABLED'
s.source_files = 'apple/**/*.{h,m,mm,cpp}'
s.ios.exclude_files = '**/*.macos.{h,m,mm,cpp}'
s.tvos.exclude_files = '**/*.macos.{h,m,mm,cpp}'
s.osx.exclude_files = '**/*.ios.{h,m,mm,cpp}'
s.requires_arc = true s.requires_arc = true
s.dependency "React" if fabric_enabled
s.dependency "React-RCTFabric" s.platforms = { :osx => "10.14", ios: '12.4', tvos: '11.0' }
s.dependency "React-Codegen" install_modules_dependencies(s)
s.dependency "RCT-Folly"
s.dependency "RCTRequired"
s.dependency "RCTTypeSafety"
s.dependency "ReactCommon/turbomodule/core"
s.subspec "common" do |ss| s.subspec "common" do |ss|
ss.source_files = "common/cpp/**/*.{cpp,h}" ss.source_files = "common/cpp/**/*.{cpp,h}"
@@ -45,12 +28,8 @@ Pod::Spec.new do |s|
ss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/common/cpp\"" } ss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/common/cpp\"" }
end end
else else
s.source_files = 'apple/**/*.{h,m,mm}' s.platforms = { :osx => "10.14", :ios => "9.0", :tvos => "9.2" }
s.exclude_files = 'apple/Utils/RNSVGFabricConversions.h' s.exclude_files = 'apple/Utils/RNSVGFabricConversions.h'
s.ios.exclude_files = '**/*.macos.{h,m,mm}'
s.tvos.exclude_files = '**/*.macos.{h,m,mm}'
s.osx.exclude_files = '**/*.ios.{h,m,mm}'
s.requires_arc = true
s.dependency 'React-Core' s.dependency 'React-Core'
end end
end end

View File

@@ -41,8 +41,7 @@ export default class SvgExample extends React.Component {
style={[ style={[
StyleSheet.absoluteFill, StyleSheet.absoluteFill,
{ alignItems: 'center', justifyContent: 'center' }, { alignItems: 'center', justifyContent: 'center' },
]} ]}>
>
<Svg height="50%" width="50%" viewBox="0 0 100 100"> <Svg height="50%" width="50%" viewBox="0 0 100 100">
<Circle <Circle
cx="50" cx="50"
@@ -131,7 +130,7 @@ import { SvgFallback } from './components/SvgFallback';
export default () => { export default () => {
const [uri, setUri] = React.useState( const [uri, setUri] = React.useState(
'https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/not_existing.svg', 'https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/not_existing.svg'
); );
return ( return (
<SvgUri <SvgUri
@@ -156,7 +155,7 @@ Try [react-native-svg-transformer](https://github.com/kristerkari/react-native-s
`metro.config.js` for react-native >= 0.72 `metro.config.js` for react-native >= 0.72
```js ```js
const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config"); const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const defaultConfig = getDefaultConfig(__dirname); const defaultConfig = getDefaultConfig(__dirname);
const { assetExts, sourceExts } = defaultConfig.resolver; const { assetExts, sourceExts } = defaultConfig.resolver;
@@ -169,12 +168,12 @@ const { assetExts, sourceExts } = defaultConfig.resolver;
*/ */
const config = { const config = {
transformer: { transformer: {
babelTransformerPath: require.resolve("react-native-svg-transformer") babelTransformerPath: require.resolve('react-native-svg-transformer'),
}, },
resolver: { resolver: {
assetExts: assetExts.filter((ext) => ext !== "svg"), assetExts: assetExts.filter((ext) => ext !== 'svg'),
sourceExts: [...sourceExts, "svg"] sourceExts: [...sourceExts, 'svg'],
} },
}; };
module.exports = mergeConfig(defaultConfig, config); module.exports = mergeConfig(defaultConfig, config);
@@ -339,8 +338,7 @@ Colors set in the Svg element are inherited by its children:
fill="blue" fill="blue"
stroke="red" stroke="red"
color="green" color="green"
viewBox="-16 -16 544 544" viewBox="-16 -16 544 544">
>
<Path <Path
d="M318.37,85.45L422.53,190.11,158.89,455,54.79,350.38ZM501.56,60.2L455.11,13.53a45.93,45.93,0,0,0-65.11,0L345.51,58.24,449.66,162.9l51.9-52.15A35.8,35.8,0,0,0,501.56,60.2ZM0.29,497.49a11.88,11.88,0,0,0,14.34,14.17l116.06-28.28L26.59,378.72Z" d="M318.37,85.45L422.53,190.11,158.89,455,54.79,350.38ZM501.56,60.2L455.11,13.53a45.93,45.93,0,0,0-65.11,0L345.51,58.24,449.66,162.9l51.9-52.15A35.8,35.8,0,0,0,501.56,60.2ZM0.29,497.49a11.88,11.88,0,0,0,14.34,14.17l116.06-28.28L26.59,378.72Z"
strokeWidth="32" strokeWidth="32"
@@ -534,8 +532,7 @@ The <Text> element is used to define text.
fontWeight="bold" fontWeight="bold"
x="100" x="100"
y="20" y="20"
textAnchor="middle" textAnchor="middle">
>
STROKED TEXT STROKED TEXT
</Text> </Text>
</Svg> </Svg>
@@ -709,8 +706,7 @@ The <Image> element allows a raster image to be included in an Svg component.
textAnchor="middle" textAnchor="middle"
fontWeight="bold" fontWeight="bold"
fontSize="16" fontSize="16"
fill="blue" fill="blue">
>
HOGWARTS HOGWARTS
</Text> </Text>
</Svg> </Svg>
@@ -733,8 +729,7 @@ The <ClipPath> SVG element defines a clipping path. A clipping path is used/refe
ry="50%" ry="50%"
fx="50%" fx="50%"
fy="50%" fy="50%"
gradientUnits="userSpaceOnUse" gradientUnits="userSpaceOnUse">
>
<Stop offset="0%" stopColor="#ff0" stopOpacity="1" /> <Stop offset="0%" stopColor="#ff0" stopOpacity="1" />
<Stop offset="100%" stopColor="#00f" stopOpacity="1" /> <Stop offset="100%" stopColor="#00f" stopOpacity="1" />
</RadialGradient> </RadialGradient>
@@ -750,8 +745,7 @@ The <ClipPath> SVG element defines a clipping path. A clipping path is used/refe
fontSize="32" fontSize="32"
fontWeight="bold" fontWeight="bold"
textAnchor="middle" textAnchor="middle"
scale="1.2" scale="1.2">
>
Q Q
</Text> </Text>
</G> </G>
@@ -829,8 +823,7 @@ The <RadialGradient> element is used to define a radial gradient. The <RadialGra
ry="55" ry="55"
fx="150" fx="150"
fy="75" fy="75"
gradientUnits="userSpaceOnUse" gradientUnits="userSpaceOnUse">
>
<Stop offset="0" stopColor="#ff0" stopOpacity="1" /> <Stop offset="0" stopColor="#ff0" stopOpacity="1" />
<Stop offset="1" stopColor="#83a" stopOpacity="1" /> <Stop offset="1" stopColor="#83a" stopOpacity="1" />
</RadialGradient> </RadialGradient>
@@ -869,8 +862,7 @@ The <Mask> element must be nested within a [&lt;Defs&gt;](#defs) tag. The [&lt;D
x1="0" x1="0"
y1="0" y1="0"
x2="800" x2="800"
y2="0" y2="0">
>
<Stop offset="0" stopColor="white" stopOpacity="0" /> <Stop offset="0" stopColor="white" stopOpacity="0" />
<Stop offset="1" stopColor="white" stopOpacity="1" /> <Stop offset="1" stopColor="white" stopOpacity="1" />
</LinearGradient> </LinearGradient>
@@ -880,8 +872,7 @@ The <Mask> element must be nested within a [&lt;Defs&gt;](#defs) tag. The [&lt;D
x="0" x="0"
y="0" y="0"
width="800" width="800"
height="300" height="300">
>
<Rect x="0" y="0" width="800" height="300" fill="url(#Gradient)" /> <Rect x="0" y="0" width="800" height="300" fill="url(#Gradient)" />
</Mask> </Mask>
<Text <Text
@@ -890,8 +881,7 @@ The <Mask> element must be nested within a [&lt;Defs&gt;](#defs) tag. The [&lt;D
y="200" y="200"
fontFamily="Verdana" fontFamily="Verdana"
fontSize="100" fontSize="100"
textAnchor="middle" textAnchor="middle">
>
Masked text Masked text
</Text> </Text>
</Defs> </Defs>
@@ -927,8 +917,7 @@ The <Pattern> element must be nested within a [&lt;Defs&gt;](#defs) tag. The [&l
y="0" y="0"
width="100" width="100"
height="100" height="100"
viewBox="0 0 10 10" viewBox="0 0 10 10">
>
<Path d="M 0 0 L 7 0 L 3.5 7 z" fill="red" stroke="blue" /> <Path d="M 0 0 L 7 0 L 3.5 7 z" fill="red" stroke="blue" />
</Pattern> </Pattern>
</Defs> </Defs>
@@ -968,8 +957,7 @@ The graphics for a marker are defined by a marker element. To indicate tha
markerUnits="strokeWidth" markerUnits="strokeWidth"
markerWidth="4" markerWidth="4"
markerHeight="3" markerHeight="3"
orient="auto" orient="auto">
>
<Path d="M 0 0 L 10 5 L 0 10 z" /> <Path d="M 0 0 L 10 5 L 0 10 z" />
</Marker> </Marker>
</Defs> </Defs>
@@ -1129,8 +1117,7 @@ export default class App extends Component {
x1="0" x1="0"
y1="0" y1="0"
x2="800" x2="800"
y2="0" y2="0">
>
<Stop offset="0" stopColor="white" stopOpacity="0.2" /> <Stop offset="0" stopColor="white" stopOpacity="0.2" />
<Stop offset="1" stopColor="white" stopOpacity="1" /> <Stop offset="1" stopColor="white" stopOpacity="1" />
</LinearGradient> </LinearGradient>
@@ -1140,8 +1127,7 @@ export default class App extends Component {
x="0" x="0"
y="0" y="0"
width="800" width="800"
height="300" height="300">
>
<Rect <Rect
x="0" x="0"
y="0" y="0"

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import renderer from 'react-test-renderer'; import renderer from 'react-test-renderer';
import { SvgCss, parse, inlineStyles } from '../src/ReactNativeSVG'; import { SvgCss, parse, inlineStyles } from '../src/ReactNativeSVG';

View File

@@ -1,7 +1,7 @@
import { Config } from '@jest/types'; import { Config } from '@jest/types';
const config: Config.InitialOptions = { const config: Config.InitialOptions = {
testPathIgnorePatterns: ['/node_modules/', '/Example/', '/TestsExample/'], testPathIgnorePatterns: ['/node_modules/', '/Example/', '/TestsExample/', '/FabricExample/'],
preset: 'react-native', preset: 'react-native',
verbose: true, verbose: true,
}; };

View File

@@ -13,11 +13,9 @@
"types": "lib/typescript/index.d.ts", "types": "lib/typescript/index.d.ts",
"react-native": "src/index.ts", "react-native": "src/index.ts",
"files": [ "files": [
"__tests__",
"android", "android",
"apple", "apple",
"common", "common",
"elements",
"lib", "lib",
"src", "src",
"RNSVG.podspec", "RNSVG.podspec",
@@ -47,8 +45,6 @@
], ],
"scripts": { "scripts": {
"bob": "bob build", "bob": "bob build",
"flow": "flow src",
"flowtyped": "flow-typed install",
"format": "yarn format-js && yarn format-ios && yarn format-java", "format": "yarn format-js && yarn format-ios && yarn format-java",
"format-ios": "find apple/ common/ -iname *.h -o -iname *.m -o -iname *.cpp -o -iname *.mm | xargs clang-format -i", "format-ios": "find apple/ common/ -iname *.h -o -iname *.m -o -iname *.cpp -o -iname *.mm | xargs clang-format -i",
"format-java": "node ./scripts/format-java.js", "format-java": "node ./scripts/format-java.js",
@@ -70,45 +66,42 @@
"css-tree": "^1.1.3" "css-tree": "^1.1.3"
}, },
"devDependencies": { "devDependencies": {
"@react-native-community/cli": "^9.0.0",
"@react-native-community/cli-platform-android": "^9.0.0",
"@react-native-community/cli-platform-ios": "^9.0.0",
"@react-native-community/eslint-config": "^3.0.2", "@react-native-community/eslint-config": "^3.0.2",
"@react-native-community/eslint-plugin": "^1.2.0", "@react-native-community/eslint-plugin": "^1.2.0",
"@react-native/babel-plugin-codegen": "^0.71.0", "@react-native/babel-plugin-codegen": "^0.71.0",
"@react-native/eslint-config": "^0.72.2",
"@types/css-tree": "^1.0.3", "@types/css-tree": "^1.0.3",
"@types/jest": "^27.5.2", "@types/jest": "^27.5.2",
"@types/node": "*", "@types/node": "*",
"@types/react": "~18.0.15", "@types/react": "^18.2.18",
"@types/react-native": "^0.70.0", "@typescript-eslint/eslint-plugin": "^5.11.0",
"@typescript-eslint/parser": "^5.11.0",
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"babel-jest": "^28.1.0", "babel-jest": "^28.1.0",
"babel-plugin-module-resolver": "^5.0.0",
"clang-format": "^1.8.0", "clang-format": "^1.8.0",
"eslint": "^8.16.0", "eslint": "^8.44.0",
"eslint-plugin-flowtype": "^8.0.3", "eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-config-standard": "^17.0.0",
"eslint-plugin-react": "^7.30.0", "eslint-import-resolver-babel-module": "^5.3.2",
"flow-bin": "^0.119.1", "eslint-plugin-import": "^2.25.4",
"flow-typed": "^3.0.0", "eslint-plugin-n": "^16.0.0",
"flowgen": "^1.10.0", "eslint-plugin-promise": "^6.1.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-standard": "^5.0.0",
"husky": "^8.0.1", "husky": "^8.0.1",
"jest": "^28.1.0", "jest": "^28.1.0",
"lint-staged": "^13.0.3", "lint-staged": "^13.0.3",
"pegjs": "^0.10.0", "pegjs": "^0.10.0",
"prettier": "^2.6.2", "prettier": "3.0.1",
"react": "^17.0.1", "react": "^18.2.0",
"react-native": "^0.64.0", "react-native": "^0.72.3",
"react-native-builder-bob": "^0.20.4", "react-native-builder-bob": "^0.20.4",
"react-native-windows": "^0.64.0", "react-native-windows": "^0.72.4",
"react-test-renderer": "^16.13.0", "react-test-renderer": "^18.2.0",
"release-it": "^14.12.5", "release-it": "^14.12.5",
"ts-node": "^10.8.0", "ts-node": "^10.8.0",
"typescript": "^4.7.2" "typescript": "^5.1.6"
},
"resolutions": {
"@react-native-community/cli-platform-android": "^9.0.0",
"@react-native-community/cli": "^9.0.0",
"@react-native-community/cli-platform-ios": "^9.0.0"
}, },
"lint-staged": { "lint-staged": {
"{src,Example}/**/*.{js,ts,tsx}": "yarn format-js", "{src,Example}/**/*.{js,ts,tsx}": "yarn format-js",

View File

@@ -1,4 +1,5 @@
import React, { useState, useEffect, Component } from 'react'; import * as React from 'react';
import { useState, useEffect, Component } from 'react';
import type { ImageSourcePropType } from 'react-native'; import type { ImageSourcePropType } from 'react-native';
import { Platform, Image } from 'react-native'; import { Platform, Image } from 'react-native';
@@ -24,12 +25,14 @@ export function isUriAnAndroidResourceIdentifier(uri?: string) {
export async function loadAndroidRawResource(uri: string) { export async function loadAndroidRawResource(uri: string) {
try { try {
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
// neeeded for new arch
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('./fabric/NativeSvgRenderableModule').default; require('./fabric/NativeSvgRenderableModule').default;
return await RNSVGRenderableModule.getRawResource(uri); return await RNSVGRenderableModule.getRawResource(uri);
} catch (e) { } catch (e) {
console.error( console.error(
'Error in RawResourceUtils while trying to natively load an Android raw resource: ', 'Error in RawResourceUtils while trying to natively load an Android raw resource: ',
e, e
); );
return null; return null;
} }
@@ -51,7 +54,7 @@ export const loadLocalRawResource =
export type LocalProps = SvgProps & { export type LocalProps = SvgProps & {
asset: ImageSourcePropType; asset: ImageSourcePropType;
override?: Object; override?: object;
}; };
export type LocalState = { xml: string | null }; export type LocalState = { xml: string | null };
@@ -69,12 +72,14 @@ export class WithLocalSvg extends Component<LocalProps, LocalState> {
componentDidMount() { componentDidMount() {
this.load(this.props.asset); this.load(this.props.asset);
} }
componentDidUpdate(prevProps: { asset: ImageSourcePropType }) { componentDidUpdate(prevProps: { asset: ImageSourcePropType }) {
const { asset } = this.props; const { asset } = this.props;
if (asset !== prevProps.asset) { if (asset !== prevProps.asset) {
this.load(asset); this.load(asset);
} }
} }
async load(asset: ImageSourcePropType) { async load(asset: ImageSourcePropType) {
try { try {
this.setState({ xml: asset ? await loadLocalRawResource(asset) : null }); this.setState({ xml: asset ? await loadLocalRawResource(asset) : null });
@@ -82,6 +87,7 @@ export class WithLocalSvg extends Component<LocalProps, LocalState> {
console.error(e); console.error(e);
} }
} }
render() { render() {
const { const {
props, props,

View File

@@ -24,7 +24,7 @@ import type { TSpanProps } from './elements/TSpan';
import type { UseProps } from './elements/Use'; import type { UseProps } from './elements/Use';
import type { GestureResponderEvent, TransformsStyle } from 'react-native'; import type { GestureResponderEvent, TransformsStyle } from 'react-native';
import { import {
// @ts-ignore // @ts-ignore it is not seen in exports
unstable_createElement as createElement, unstable_createElement as createElement,
} from 'react-native'; } from 'react-native';
import type { import type {
@@ -36,11 +36,11 @@ import SvgTouchableMixin from './lib/SvgTouchableMixin';
import { resolve } from './lib/resolve'; import { resolve } from './lib/resolve';
import { transformsArrayToProps } from './lib/extract/extractTransform'; import { transformsArrayToProps } from './lib/extract/extractTransform';
type BlurEvent = Object; type BlurEvent = object;
type FocusEvent = Object; type FocusEvent = object;
type PressEvent = Object; type PressEvent = object;
type LayoutEvent = Object; type LayoutEvent = object;
type EdgeInsetsProp = Object; type EdgeInsetsProp = object;
interface BaseProps { interface BaseProps {
accessible?: boolean; accessible?: boolean;
@@ -48,7 +48,7 @@ interface BaseProps {
accessibilityHint?: string; accessibilityHint?: string;
accessibilityIgnoresInvertColors?: boolean; accessibilityIgnoresInvertColors?: boolean;
accessibilityRole?: string; accessibilityRole?: string;
accessibilityState?: Object; accessibilityState?: object;
delayLongPress?: number; delayLongPress?: number;
delayPressIn?: number; delayPressIn?: number;
delayPressOut?: number; delayPressOut?: number;
@@ -88,7 +88,7 @@ interface BaseProps {
forwardedRef?: forwardedRef?:
| React.RefCallback<SVGElement> | React.RefCallback<SVGElement>
| React.MutableRefObject<SVGElement | null>; | React.MutableRefObject<SVGElement | null>;
style?: Iterable<{}>; style?: Iterable<unknown>;
// different tranform props // different tranform props
gradientTransform?: TransformProps['transform']; gradientTransform?: TransformProps['transform'];
@@ -111,7 +111,7 @@ function stringifyTransformProps(transformProps: TransformProps) {
transformArray.push( transformArray.push(
`translate(${transformProps.translateX || 0}, ${ `translate(${transformProps.translateX || 0}, ${
transformProps.translateY || 0 transformProps.translateY || 0
})`, })`
); );
} }
if (transformProps.scale != null) { if (transformProps.scale != null) {
@@ -119,7 +119,7 @@ function stringifyTransformProps(transformProps: TransformProps) {
} }
if (transformProps.scaleX != null || transformProps.scaleY != null) { if (transformProps.scaleX != null || transformProps.scaleY != null) {
transformArray.push( transformArray.push(
`scale(${transformProps.scaleX || 1}, ${transformProps.scaleY || 1})`, `scale(${transformProps.scaleX || 1}, ${transformProps.scaleY || 1})`
); );
} }
// rotation maps to rotate, not to collide with the text rotate attribute (which acts per glyph rather than block) // rotation maps to rotate, not to collide with the text rotate attribute (which acts per glyph rather than block)
@@ -137,7 +137,7 @@ function stringifyTransformProps(transformProps: TransformProps) {
function parseTransformProp( function parseTransformProp(
transform: TransformProps['transform'], transform: TransformProps['transform'],
props?: BaseProps, props?: BaseProps
) { ) {
const transformArray: string[] = []; const transformArray: string[] = [];
@@ -148,7 +148,7 @@ function parseTransformProp(
transformArray.push(`matrix(${transform.join(' ')})`); transformArray.push(`matrix(${transform.join(' ')})`);
} else { } else {
const stringifiedProps = transformsArrayToProps( const stringifiedProps = transformsArrayToProps(
transform as TransformsStyle['transform'], transform as TransformsStyle['transform']
); );
transformArray.push(...stringifyTransformProps(stringifiedProps)); transformArray.push(...stringifyTransformProps(stringifiedProps));
} }
@@ -170,7 +170,7 @@ function parseTransformProp(
*/ */
const prepare = <T extends BaseProps>( const prepare = <T extends BaseProps>(
self: WebShape<T>, self: WebShape<T>,
props = self.props, props = self.props
) => { ) => {
const { const {
transform, transform,
@@ -199,8 +199,8 @@ const prepare = <T extends BaseProps>(
gradientTransform?: string; gradientTransform?: string;
patternTransform?: string; patternTransform?: string;
'transform-origin'?: string; 'transform-origin'?: string;
style?: {}; style?: object;
ref?: {}; ref?: unknown;
} = { } = {
...(hasTouchableProperty(props) ...(hasTouchableProperty(props)
? { ? {
@@ -262,14 +262,12 @@ const prepare = <T extends BaseProps>(
const getBoundingClientRect = (node: SVGElement) => { const getBoundingClientRect = (node: SVGElement) => {
if (node) { if (node) {
// @ts-ignore
const isElement = node.nodeType === 1; /* Node.ELEMENT_NODE */ const isElement = node.nodeType === 1; /* Node.ELEMENT_NODE */
// @ts-ignore
if (isElement && typeof node.getBoundingClientRect === 'function') { if (isElement && typeof node.getBoundingClientRect === 'function') {
// @ts-ignore
return node.getBoundingClientRect(); return node.getBoundingClientRect();
} }
} }
throw new Error('Can not get boundingClientRect of ' + node || 'undefined');
}; };
const measureLayout = ( const measureLayout = (
@@ -280,14 +278,13 @@ const measureLayout = (
width: number, width: number,
height: number, height: number,
left: number, left: number,
top: number, top: number
) => void, ) => void
) => { ) => {
// @ts-ignore const relativeNode = node?.parentNode;
const relativeNode = node && node.parentNode;
if (relativeNode) { if (relativeNode) {
setTimeout(() => { setTimeout(() => {
// @ts-ignore // @ts-expect-error TODO: handle it better
const relativeRect = getBoundingClientRect(relativeNode); const relativeRect = getBoundingClientRect(relativeNode);
const { height, left, top, width } = getBoundingClientRect(node); const { height, left, top, width } = getBoundingClientRect(node);
const x = left - relativeRect.left; const x = left - relativeRect.left;
@@ -297,20 +294,18 @@ const measureLayout = (
} }
}; };
function remeasure() { // eslint-disable-next-line @typescript-eslint/no-explicit-any
// @ts-ignore function remeasure(this: any) {
const tag = this.state.touchable.responderID; const tag = this.state.touchable.responderID;
if (tag == null) { if (tag === null) {
return; return;
} }
// @ts-ignore
measureLayout(tag, this._handleQueryLayout); measureLayout(tag, this._handleQueryLayout);
} }
export class WebShape< export class WebShape<
P extends BaseProps = BaseProps, P extends BaseProps = BaseProps,
C = {}, > extends React.Component<P> {
> extends React.Component<P, C> {
[x: string]: unknown; [x: string]: unknown;
protected tag?: React.ElementType; protected tag?: React.ElementType;
protected prepareProps(props: P) { protected prepareProps(props: P) {
@@ -319,6 +314,7 @@ export class WebShape<
elementRef = elementRef =
React.createRef<SVGElement>() as React.MutableRefObject<SVGElement | null>; React.createRef<SVGElement>() as React.MutableRefObject<SVGElement | null>;
lastMergedProps: Partial<P> = {}; lastMergedProps: Partial<P> = {};
/** /**
@@ -329,7 +325,7 @@ export class WebShape<
{}, {},
this.props, this.props,
this.lastMergedProps, this.lastMergedProps,
props.style, props.style
); );
this.lastMergedProps = merged; this.lastMergedProps = merged;
const clean = prepare(this, this.prepareProps(merged)); const clean = prepare(this, this.prepareProps(merged));
@@ -343,15 +339,16 @@ export class WebShape<
break; break;
case 'style': case 'style':
// style can be an object here or an array, so we convert it to an array and assign each element // style can be an object here or an array, so we convert it to an array and assign each element
for (const partialStyle of ([] as {}[]).concat(clean.style ?? [])) { for (const partialStyle of ([] as unknown[]).concat(
// @ts-expect-error "DOM" is not part of `compilerOptions.lib` clean.style ?? []
)) {
Object.assign(current.style, partialStyle); Object.assign(current.style, partialStyle);
} }
break; break;
default: default:
// apply all other incoming prop updates as attributes on the node // apply all other incoming prop updates as attributes on the node
// same logic as in https://github.com/software-mansion/react-native-reanimated/blob/d04720c82f5941532991b235787285d36d717247/src/reanimated2/js-reanimated/index.ts#L38-L39 // same logic as in https://github.com/software-mansion/react-native-reanimated/blob/d04720c82f5941532991b235787285d36d717247/src/reanimated2/js-reanimated/index.ts#L38-L39
// @ts-expect-error "DOM" is not part of `compilerOptions.lib` // @ts-expect-error TODO: fix this
current.setAttribute(camelCaseToDashed(cleanAttribute), cleanValue); current.setAttribute(camelCaseToDashed(cleanAttribute), cleanValue);
break; break;
} }
@@ -361,17 +358,19 @@ export class WebShape<
_remeasureMetricsOnActivation: () => void; _remeasureMetricsOnActivation: () => void;
touchableHandleStartShouldSetResponder?: ( touchableHandleStartShouldSetResponder?: (
e: GestureResponderEvent, e: GestureResponderEvent
) => boolean; ) => boolean;
touchableHandleResponderMove?: (e: GestureResponderEvent) => void; touchableHandleResponderMove?: (e: GestureResponderEvent) => void;
touchableHandleResponderGrant?: (e: GestureResponderEvent) => void; touchableHandleResponderGrant?: (e: GestureResponderEvent) => void;
touchableHandleResponderRelease?: (e: GestureResponderEvent) => void; touchableHandleResponderRelease?: (e: GestureResponderEvent) => void;
touchableHandleResponderTerminate?: (e: GestureResponderEvent) => void; touchableHandleResponderTerminate?: (e: GestureResponderEvent) => void;
touchableHandleResponderTerminationRequest?: ( touchableHandleResponderTerminationRequest?: (
e: GestureResponderEvent, e: GestureResponderEvent
) => boolean; ) => boolean;
constructor(props: P, context: C) {
super(props, context); constructor(props: P) {
super(props);
// Do not attach touchable mixin handlers if SVG element doesn't have a touchable prop // Do not attach touchable mixin handlers if SVG element doesn't have a touchable prop
if (hasTouchableProperty(props)) { if (hasTouchableProperty(props)) {
@@ -384,13 +383,13 @@ export class WebShape<
render(): JSX.Element { render(): JSX.Element {
if (!this.tag) { if (!this.tag) {
throw new Error( throw new Error(
'When extending `WebShape` you need to overwrite either `tag` or `render`!', 'When extending `WebShape` you need to overwrite either `tag` or `render`!'
); );
} }
this.lastMergedProps = {}; this.lastMergedProps = {};
return createElement( return createElement(
this.tag, this.tag,
prepare(this, this.prepareProps(this.props)), prepare(this, this.prepareProps(this.props))
); );
} }
} }
@@ -467,7 +466,7 @@ function encodeSvg(svgString: string) {
'<svg', '<svg',
~svgString.indexOf('xmlns') ~svgString.indexOf('xmlns')
? '<svg' ? '<svg'
: '<svg xmlns="http://www.w3.org/2000/svg"', : '<svg xmlns="http://www.w3.org/2000/svg"'
) )
.replace(/"/g, "'") .replace(/"/g, "'")
.replace(/%/g, '%25') .replace(/%/g, '%25')
@@ -483,11 +482,11 @@ export class Svg extends WebShape<BaseProps & SvgProps> {
tag = 'svg' as const; tag = 'svg' as const;
toDataURL( toDataURL(
callback: (data: string) => void, callback: (data: string) => void,
options: { width?: number; height?: number } = {}, options: { width?: number; height?: number } = {}
) { ) {
const ref = this.elementRef.current; const ref = this.elementRef.current;
if (ref == null) { if (ref === null) {
return; return;
} }
@@ -496,18 +495,14 @@ export class Svg extends WebShape<BaseProps & SvgProps> {
const width = Number(options.width) || rect.width; const width = Number(options.width) || rect.width;
const height = Number(options.height) || rect.height; const height = Number(options.height) || rect.height;
// @ts-expect-error "DOM" is not part of `compilerOptions.lib`
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', `0 0 ${rect.width} ${rect.height}`); svg.setAttribute('viewBox', `0 0 ${rect.width} ${rect.height}`);
svg.setAttribute('width', String(width)); svg.setAttribute('width', String(width));
svg.setAttribute('height', String(height)); svg.setAttribute('height', String(height));
// @ts-expect-error "DOM" is not part of `compilerOptions.lib`
svg.appendChild(ref.cloneNode(true)); svg.appendChild(ref.cloneNode(true));
// @ts-expect-error "DOM" is not part of `compilerOptions.lib`
const img = new window.Image(); const img = new window.Image();
img.onload = () => { img.onload = () => {
// @ts-expect-error "DOM" is not part of `compilerOptions.lib`
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = width; canvas.width = width;
canvas.height = height; canvas.height = height;
@@ -517,8 +512,7 @@ export class Svg extends WebShape<BaseProps & SvgProps> {
}; };
img.src = `data:image/svg+xml;utf8,${encodeSvg( img.src = `data:image/svg+xml;utf8,${encodeSvg(
// @ts-expect-error "DOM" is not part of `compilerOptions.lib` new window.XMLSerializer().serializeToString(svg)
new window.XMLSerializer().serializeToString(svg),
)}`; )}`;
} }
} }

View File

@@ -1,4 +1,5 @@
import React, { Component, useEffect, useMemo, useState } from 'react'; import * as React from 'react';
import { Component, useEffect, useMemo, useState } from 'react';
import type { import type {
JsxAST, JsxAST,
Middleware, Middleware,
@@ -76,10 +77,10 @@ function getAttributeValue(elem: XmlAST, name: string): string {
// takes an array of nodes, and removes any duplicates, as well as any nodes // takes an array of nodes, and removes any duplicates, as well as any nodes
// whose ancestors are also in the array // whose ancestors are also in the array
function removeSubsets(nodes: Array<XmlAST | string>): Array<XmlAST | string> { function removeSubsets(nodes: Array<XmlAST | string>): Array<XmlAST | string> {
let idx = nodes.length, let idx = nodes.length;
node, let node;
ancestor, let ancestor;
replace; let replace;
// Check if each node (or one of its ancestors) is already contained in the // Check if each node (or one of its ancestors) is already contained in the
// array. // array.
@@ -111,12 +112,12 @@ function removeSubsets(nodes: Array<XmlAST | string>): Array<XmlAST | string> {
// does at least one of passed element nodes pass the test predicate? // does at least one of passed element nodes pass the test predicate?
function existsOne( function existsOne(
predicate: (v: XmlAST) => boolean, predicate: (v: XmlAST) => boolean,
elems: Array<XmlAST | string>, elems: Array<XmlAST | string>
): boolean { ): boolean {
return elems.some( return elems.some(
(elem) => (elem) =>
typeof elem === 'object' && typeof elem === 'object' &&
(predicate(elem) || existsOne(predicate, elem.children)), (predicate(elem) || existsOne(predicate, elem.children))
); );
} }
@@ -131,20 +132,21 @@ function getSiblings(node: XmlAST | string): Array<XmlAST | string> {
// does the element have the named attribute? // does the element have the named attribute?
function hasAttrib(elem: XmlAST, name: string): boolean { function hasAttrib(elem: XmlAST, name: string): boolean {
return elem.props.hasOwnProperty(name); return Object.prototype.hasOwnProperty.call(elem.props, name);
} }
// finds the first node in the array that matches the test predicate, or one // finds the first node in the array that matches the test predicate, or one
// of its children // of its children
function findOne( function findOne(
predicate: (v: XmlAST) => boolean, predicate: (v: XmlAST) => boolean,
elems: Array<XmlAST | string>, elems: Array<XmlAST | string>
): XmlAST | null { ): XmlAST | null {
let elem: XmlAST | null = null; let elem: XmlAST | null = null;
for (let i = 0, l = elems.length; i < l && !elem; i++) { for (let i = 0, l = elems.length; i < l && !elem; i++) {
const node = elems[i]; const node = elems[i];
if (typeof node === 'string') { if (typeof node === 'string') {
/* empty */
} else if (predicate(node)) { } else if (predicate(node)) {
elem = node; elem = node;
} else { } else {
@@ -163,7 +165,7 @@ function findOne(
function findAll( function findAll(
predicate: (v: XmlAST) => boolean, predicate: (v: XmlAST) => boolean,
nodes: Array<XmlAST | string>, nodes: Array<XmlAST | string>,
result: Array<XmlAST> = [], result: Array<XmlAST> = []
): Array<XmlAST> { ): Array<XmlAST> {
for (let i = 0, j = nodes.length; i < j; i++) { for (let i = 0, j = nodes.length; i < j; i++) {
const node = nodes[i]; const node = nodes[i];
@@ -287,10 +289,10 @@ function filterByPseudos(selectors: FlatSelectorList) {
csstree.generate({ csstree.generate({
type: 'Selector', type: 'Selector',
children: new List<CssNode>().fromArray( children: new List<CssNode>().fromArray(
pseudos.map((pseudo) => pseudo.item.data), pseudos.map((pseudo) => pseudo.item.data)
),
}),
), ),
})
)
); );
} }
// usePseudos Array with strings of single or sequence of pseudo-elements and/or -classes that should pass // usePseudos Array with strings of single or sequence of pseudo-elements and/or -classes that should pass
@@ -304,7 +306,7 @@ const usePseudos = [''];
*/ */
function cleanPseudos(selectors: FlatSelectorList) { function cleanPseudos(selectors: FlatSelectorList) {
selectors.forEach(({ pseudos }) => selectors.forEach(({ pseudos }) =>
pseudos.forEach((pseudo) => pseudo.list.remove(pseudo.item)), pseudos.forEach((pseudo) => pseudo.list.remove(pseudo.item))
); );
} }
@@ -332,11 +334,11 @@ function specificity(selector: Selector): Specificity {
case 'PseudoClassSelector': case 'PseudoClassSelector':
switch (node.name.toLowerCase()) { switch (node.name.toLowerCase()) {
case 'not': case 'not': {
const children = (node as PseudoClassSelector).children; const children = (node as PseudoClassSelector).children;
children && children.each(walk); children && children.each(walk);
break; break;
}
case 'before': case 'before':
case 'after': case 'after':
case 'first-line': case 'first-line':
@@ -355,7 +357,7 @@ function specificity(selector: Selector): Specificity {
C++; C++;
break; break;
case 'TypeSelector': case 'TypeSelector': {
// ignore universal selector // ignore universal selector
const { name } = node; const { name } = node;
if (name.charAt(name.length - 1) !== '*') { if (name.charAt(name.length - 1) !== '*') {
@@ -363,6 +365,7 @@ function specificity(selector: Selector): Specificity {
} }
break; break;
} }
}
}); });
return [A, B, C]; return [A, B, C];
@@ -378,7 +381,7 @@ function specificity(selector: Selector): Specificity {
*/ */
function compareSpecificity( function compareSpecificity(
aSpecificity: Specificity, aSpecificity: Specificity,
bSpecificity: Specificity, bSpecificity: Specificity
): number { ): number {
for (let i = 0; i < 4; i += 1) { for (let i = 0; i < 4; i += 1) {
if (aSpecificity[i] < bSpecificity[i]) { if (aSpecificity[i] < bSpecificity[i]) {
@@ -512,7 +515,7 @@ function CSSStyleDeclaration(ast: XmlAST) {
try { try {
const declarations = csstree.parse( const declarations = csstree.parse(
styles, styles,
declarationParseProps, declarationParseProps
) as DeclarationList; ) as DeclarationList;
declarations.children.each((node) => { declarations.children.each((node) => {
try { try {
@@ -527,7 +530,7 @@ function CSSStyleDeclaration(ast: XmlAST) {
) { ) {
console.warn( console.warn(
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " + "Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
styleError, styleError
); );
} }
} }
@@ -535,7 +538,7 @@ function CSSStyleDeclaration(ast: XmlAST) {
} catch (parseError) { } catch (parseError) {
console.warn( console.warn(
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " + "Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
parseError, parseError
); );
} }
} }
@@ -559,7 +562,9 @@ function initStyle(selectedEl: XmlAST): StyledAST {
*/ */
function closestElem(node: XmlAST, elemName: string) { function closestElem(node: XmlAST, elemName: string) {
let elem: XmlAST | null = node; let elem: XmlAST | null = node;
while ((elem = elem.parent) && elem.tag !== elemName) {} while ((elem = elem.parent) && elem.tag !== elemName) {
/* empty */
}
return elem; return elem;
} }
@@ -586,7 +591,7 @@ const parseProps = {
* @author modified by: msand <msand@abo.fi> * @author modified by: msand <msand@abo.fi>
*/ */
export const inlineStyles: Middleware = function inlineStyles( export const inlineStyles: Middleware = function inlineStyles(
document: XmlAST, document: XmlAST
) { ) {
// collect <style/>s // collect <style/>s
const styleElements = cssSelect('style', document, cssSelectOpts); const styleElements = cssSelect('style', document, cssSelectOpts);
@@ -598,7 +603,7 @@ export const inlineStyles: Middleware = function inlineStyles(
const selectors: FlatSelectorList = []; const selectors: FlatSelectorList = [];
for (let element of styleElements) { for (const element of styleElements) {
const { children } = element; const { children } = element;
if (!children.length || closestElem(element, 'foreignObject')) { if (!children.length || closestElem(element, 'foreignObject')) {
// skip empty <style/>s or <foreignObject> content. // skip empty <style/>s or <foreignObject> content.
@@ -612,7 +617,7 @@ export const inlineStyles: Middleware = function inlineStyles(
} catch (parseError) { } catch (parseError) {
console.warn( console.warn(
'Warning: Parse error of styles of <style/> element, skipped. Error details: ' + 'Warning: Parse error of styles of <style/> element, skipped. Error details: ' +
parseError, parseError
); );
} }
} }
@@ -630,7 +635,7 @@ export const inlineStyles: Middleware = function inlineStyles(
const sortedSelectors = sortSelectors(selectorsPseudo).reverse(); const sortedSelectors = sortSelectors(selectorsPseudo).reverse();
// match selectors // match selectors
for (let { rule, item } of sortedSelectors) { for (const { rule, item } of sortedSelectors) {
if (rule === null) { if (rule === null) {
continue; continue;
} }
@@ -638,7 +643,7 @@ export const inlineStyles: Middleware = function inlineStyles(
try { try {
// apply <style/> to matched elements // apply <style/> to matched elements
const matched = cssSelect(selectorStr, document, cssSelectOpts).map( const matched = cssSelect(selectorStr, document, cssSelectOpts).map(
initStyle, initStyle
); );
if (matched.length === 0) { if (matched.length === 0) {
@@ -655,7 +660,7 @@ export const inlineStyles: Middleware = function inlineStyles(
const name = property.trim(); const name = property.trim();
const camel = camelCase(name); const camel = camelCase(name);
const val = csstree.generate(value).trim(); const val = csstree.generate(value).trim();
for (let element of matched) { for (const element of matched) {
const { style, priority } = element; const { style, priority } = element;
const current = priority.get(name); const current = priority.get(name);
if (current === undefined || current < important) { if (current === undefined || current < important) {
@@ -671,7 +676,7 @@ export const inlineStyles: Middleware = function inlineStyles(
'Warning: Syntax error when trying to select \n\n' + 'Warning: Syntax error when trying to select \n\n' +
selectorStr + selectorStr +
'\n\n, skipped. Error details: ' + '\n\n, skipped. Error details: ' +
selectError, selectError
); );
continue; continue;
} }
@@ -686,7 +691,7 @@ export function SvgCss(props: XmlProps) {
const { xml, override } = props; const { xml, override } = props;
const ast = useMemo<JsxAST | null>( const ast = useMemo<JsxAST | null>(
() => (xml !== null ? parse(xml, inlineStyles) : null), () => (xml !== null ? parse(xml, inlineStyles) : null),
[xml], [xml]
); );
return <SvgAst ast={ast} override={override || props} />; return <SvgAst ast={ast} override={override || props} />;
} }
@@ -714,12 +719,14 @@ export class SvgWithCss extends Component<XmlProps, XmlState> {
componentDidMount() { componentDidMount() {
this.parse(this.props.xml); this.parse(this.props.xml);
} }
componentDidUpdate(prevProps: { xml: string | null }) { componentDidUpdate(prevProps: { xml: string | null }) {
const { xml } = this.props; const { xml } = this.props;
if (xml !== prevProps.xml) { if (xml !== prevProps.xml) {
this.parse(xml); this.parse(xml);
} }
} }
parse(xml: string | null) { parse(xml: string | null) {
try { try {
this.setState({ ast: xml ? parse(xml, inlineStyles) : null }); this.setState({ ast: xml ? parse(xml, inlineStyles) : null });
@@ -727,6 +734,7 @@ export class SvgWithCss extends Component<XmlProps, XmlState> {
this.props.onError ? this.props.onError(e as Error) : console.error(e); this.props.onError ? this.props.onError(e as Error) : console.error(e);
} }
} }
render() { render() {
const { const {
props, props,
@@ -741,12 +749,14 @@ export class SvgWithCssUri extends Component<UriProps, UriState> {
componentDidMount() { componentDidMount() {
this.fetch(this.props.uri); this.fetch(this.props.uri);
} }
componentDidUpdate(prevProps: { uri: string | null }) { componentDidUpdate(prevProps: { uri: string | null }) {
const { uri } = this.props; const { uri } = this.props;
if (uri !== prevProps.uri) { if (uri !== prevProps.uri) {
this.fetch(uri); this.fetch(uri);
} }
} }
async fetch(uri: string | null) { async fetch(uri: string | null) {
try { try {
this.setState({ xml: uri ? await fetchText(uri) : null }); this.setState({ xml: uri ? await fetchText(uri) : null });
@@ -754,6 +764,7 @@ export class SvgWithCssUri extends Component<UriProps, UriState> {
this.props.onError ? this.props.onError(e as Error) : console.error(e); this.props.onError ? this.props.onError(e as Error) : console.error(e);
} }
} }
render() { render() {
const { const {
props, props,

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps'; import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps';
import type { CommonPathProps, NumberProp } from '../lib/extract/types'; import type { CommonPathProps, NumberProp } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import { extract } from '../lib/extract/extractProps'; import { extract } from '../lib/extract/extractProps';
import Shape from './Shape'; import Shape from './Shape';
import RNSVGClipPath from '../fabric/ClipPathNativeComponent'; import RNSVGClipPath from '../fabric/ClipPathNativeComponent';

View File

@@ -1,7 +1,8 @@
import React, { Component } from 'react'; import * as React from 'react';
import { Component } from 'react';
import RNSVGDefs from '../fabric/DefsNativeComponent'; import RNSVGDefs from '../fabric/DefsNativeComponent';
export default class Defs extends Component<React.PropsWithChildren<{}>> { export default class Defs extends Component<React.PropsWithChildren> {
static displayName = 'Defs'; static displayName = 'Defs';
render() { render() {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps'; import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps';
import type { CommonPathProps, NumberProp } from '../lib/extract/types'; import type { CommonPathProps, NumberProp } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import { import {
withoutXY, withoutXY,
stringifyPropsForFabric, stringifyPropsForFabric,
@@ -37,8 +37,7 @@ export default class ForeignObject extends G<ForeignObjectProps> {
this.refMethod(ref as (ForeignObject & NativeMethods) | null) this.refMethod(ref as (ForeignObject & NativeMethods) | null)
} }
{...withoutXY(this, props)} {...withoutXY(this, props)}
{...foreignObjectProps} {...foreignObjectProps}>
>
{children} {children}
</RNSVGForeignObject> </RNSVGForeignObject>
); );

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import extractProps, { propsAndStyles } from '../lib/extract/extractProps'; import extractProps, { propsAndStyles } from '../lib/extract/extractProps';
import { extractFont } from '../lib/extract/extractText'; import { extractFont } from '../lib/extract/extractText';
import extractTransform from '../lib/extract/extractTransform'; import extractTransform from '../lib/extract/extractTransform';
@@ -24,7 +24,7 @@ export default class G<P> extends Shape<GProps & P> {
props: GProps & props: GProps &
P & { P & {
matrix?: number[]; matrix?: number[];
}, }
) => { ) => {
const matrix = !props.matrix && extractTransform(props); const matrix = !props.matrix && extractTransform(props);
if (matrix) { if (matrix) {
@@ -44,16 +44,16 @@ export default class G<P> extends Shape<GProps & P> {
return ( return (
<RNSVGGroup <RNSVGGroup
ref={(ref) => this.refMethod(ref as (G<P> & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (G<P> & NativeMethods) | null)}
{...extractedProps} {...extractedProps}>
>
{props.children} {props.children}
</RNSVGGroup> </RNSVGGroup>
); );
} }
} }
const hasProps = (obj: {}) => { const hasProps = (obj: object) => {
for (let _ in obj) { // eslint-disable-next-line no-unreachable-loop
for (const _ in obj) {
return true; return true;
} }
return false; return false;

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import type { ImageProps as RNImageProps, NativeMethods } from 'react-native'; import type { ImageProps as RNImageProps, NativeMethods } from 'react-native';
import { Image } from 'react-native'; import { Image } from 'react-native';
import { alignEnum, meetOrSliceTypes } from '../lib/extract/extractViewBox'; import { alignEnum, meetOrSliceTypes } from '../lib/extract/extractViewBox';
@@ -64,7 +64,7 @@ export default class SvgImage extends Shape<ImageProps> {
src: !href src: !href
? null ? null
: Image.resolveAssetSource( : Image.resolveAssetSource(
typeof href === 'string' ? { uri: href } : href, typeof href === 'string' ? { uri: href } : href
), ),
}; };
return ( return (

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps'; import { extract, stringifyPropsForFabric } from '../lib/extract/extractProps';
import type { CommonPathProps, NumberProp } from '../lib/extract/types'; import type { CommonPathProps, NumberProp } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';

View File

@@ -1,5 +1,5 @@
import type { ReactElement } from 'react'; import type { ReactElement } from 'react';
import React from 'react'; import * as React from 'react';
import extractGradient from '../lib/extract/extractGradient'; import extractGradient from '../lib/extract/extractGradient';
import type { NumberProp, TransformProps, Units } from '../lib/extract/types'; import type { NumberProp, TransformProps, Units } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import extractViewBox from '../lib/extract/extractViewBox'; import extractViewBox from '../lib/extract/extractViewBox';
import type { NumberProp } from '../lib/extract/types'; import type { NumberProp } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';
@@ -64,8 +64,7 @@ export default class Marker extends Shape<MarkerProps> {
<RNSVGMarker <RNSVGMarker
ref={(ref) => this.refMethod(ref as (Marker & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (Marker & NativeMethods) | null)}
{...markerProps} {...markerProps}
{...extractViewBox({ viewBox, preserveAspectRatio })} {...extractViewBox({ viewBox, preserveAspectRatio })}>
>
{children} {children}
</RNSVGMarker> </RNSVGMarker>
); );

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import { import {
stringifyPropsForFabric, stringifyPropsForFabric,
withoutXY, withoutXY,
@@ -53,8 +53,7 @@ export default class Mask extends Shape<MaskProps> {
ref={(ref) => this.refMethod(ref as (Mask & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (Mask & NativeMethods) | null)}
{...withoutXY(this, props)} {...withoutXY(this, props)}
{...strigifiedMaskProps} {...strigifiedMaskProps}
{...maskProps} {...maskProps}>
>
{children} {children}
</RNSVGMask> </RNSVGMask>
); );

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { extract } from '../lib/extract/extractProps'; import { extract } from '../lib/extract/extractProps';
import Shape from './Shape'; import Shape from './Shape';
import RNSVGPath from '../fabric/PathNativeComponent'; import RNSVGPath from '../fabric/PathNativeComponent';

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import extractTransform from '../lib/extract/extractTransform'; import extractTransform from '../lib/extract/extractTransform';
import extractViewBox from '../lib/extract/extractViewBox'; import extractViewBox from '../lib/extract/extractViewBox';
import type { NumberProp, TransformProps, Units } from '../lib/extract/types'; import type { NumberProp, TransformProps, Units } from '../lib/extract/types';
@@ -68,8 +68,7 @@ export default class Pattern extends Shape<PatternProps> {
ref={(ref) => this.refMethod(ref as (Pattern & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (Pattern & NativeMethods) | null)}
{...strigifiedPatternProps} {...strigifiedPatternProps}
{...patternProps} {...patternProps}
{...extractViewBox({ viewBox, preserveAspectRatio })} {...extractViewBox({ viewBox, preserveAspectRatio })}>
>
{children} {children}
</RNSVGPattern> </RNSVGPattern>
); );

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import Path from './Path'; import Path from './Path';
import Shape from './Shape'; import Shape from './Shape';
import type { CommonPathProps, NumberProp } from '../lib/extract/types'; import type { CommonPathProps, NumberProp } from '../lib/extract/types';
@@ -19,7 +19,7 @@ export default class Polygon extends Shape<PolygonProps> {
setNativeProps = ( setNativeProps = (
props: PolygonProps & { props: PolygonProps & {
d?: string; d?: string;
}, }
) => { ) => {
const { points } = props; const { points } = props;
if (points) { if (points) {

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import Path from './Path'; import Path from './Path';
import Shape from './Shape'; import Shape from './Shape';
import type { CommonPathProps, NumberProp } from '../lib/extract/types'; import type { CommonPathProps, NumberProp } from '../lib/extract/types';
@@ -19,7 +19,7 @@ export default class Polyline extends Shape<PolylineProps> {
setNativeProps = ( setNativeProps = (
props: PolylineProps & { props: PolylineProps & {
d?: string; d?: string;
}, }
) => { ) => {
const { points } = props; const { points } = props;
if (points) { if (points) {

View File

@@ -1,5 +1,5 @@
import type { ReactElement } from 'react'; import type { ReactElement } from 'react';
import React from 'react'; import * as React from 'react';
import extractGradient from '../lib/extract/extractGradient'; import extractGradient from '../lib/extract/extractGradient';
import type { NumberProp, TransformProps, Units } from '../lib/extract/types'; import type { NumberProp, TransformProps, Units } from '../lib/extract/types';
import Shape from './Shape'; import Shape from './Shape';

View File

@@ -1,4 +1,4 @@
import React from 'react'; import * as React from 'react';
import { import {
stringifyPropsForFabric, stringifyPropsForFabric,
withoutXY, withoutXY,

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { Component } from 'react'; import { Component } from 'react';
import SvgTouchableMixin from '../lib/SvgTouchableMixin'; import SvgTouchableMixin from '../lib/SvgTouchableMixin';
import extractBrush from '../lib/extract/extractBrush'; import extractBrush from '../lib/extract/extractBrush';
@@ -29,7 +30,6 @@ export interface Point {
} }
export interface SVGPoint extends Point { export interface SVGPoint extends Point {
constructor(point?: Point): SVGPoint;
matrixTransform(matrix: Matrix): SVGPoint; matrixTransform(matrix: Matrix): SVGPoint;
} }
@@ -39,7 +39,7 @@ export interface Rect {
width: number; width: number;
height: number; height: number;
} }
export interface SVGRect extends Rect {} export type SVGRect = Rect;
export interface Matrix { export interface Matrix {
a: number; a: number;
@@ -51,7 +51,6 @@ export interface Matrix {
} }
export interface SVGMatrix extends Matrix { export interface SVGMatrix extends Matrix {
constructor(matrix?: Matrix): SVGMatrix;
multiply(secondMatrix: Matrix): SVGMatrix; multiply(secondMatrix: Matrix): SVGMatrix;
inverse(): SVGMatrix; inverse(): SVGMatrix;
translate(x: number, y: number): SVGMatrix; translate(x: number, y: number): SVGMatrix;
@@ -65,7 +64,7 @@ export interface SVGMatrix extends Matrix {
skewY(angle: number): SVGMatrix; skewY(angle: number): SVGMatrix;
} }
export function multiply_matrices(l: Matrix, r: Matrix): Matrix { export function multiplyMatrices(l: Matrix, r: Matrix): Matrix {
const { a: al, b: bl, c: cl, d: dl, e: el, f: fl } = l; const { a: al, b: bl, c: cl, d: dl, e: el, f: fl } = l;
const { a: ar, b: br, c: cr, d: dr, e: er, f: fr } = r; const { a: ar, b: br, c: cr, d: dr, e: er, f: fr } = r;
@@ -112,88 +111,99 @@ export class SVGMatrix implements SVGMatrix {
this.f = 0; this.f = 0;
} }
} }
multiply(secondMatrix: Matrix): SVGMatrix { multiply(secondMatrix: Matrix): SVGMatrix {
return new SVGMatrix(multiply_matrices(this, secondMatrix)); return new SVGMatrix(multiplyMatrices(this, secondMatrix));
} }
inverse(): SVGMatrix { inverse(): SVGMatrix {
return new SVGMatrix(invert(this)); return new SVGMatrix(invert(this));
} }
translate(x: number, y: number): SVGMatrix { translate(x: number, y: number): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { a: 1, b: 0, c: 0, d: 1, e: x, f: y }), multiplyMatrices(this, { a: 1, b: 0, c: 0, d: 1, e: x, f: y })
); );
} }
scale(scaleFactor: number): SVGMatrix { scale(scaleFactor: number): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { multiplyMatrices(this, {
a: scaleFactor, a: scaleFactor,
b: 0, b: 0,
c: 0, c: 0,
d: scaleFactor, d: scaleFactor,
e: 0, e: 0,
f: 0, f: 0,
}), })
); );
} }
scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix { scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { multiplyMatrices(this, {
a: scaleFactorX, a: scaleFactorX,
b: 0, b: 0,
c: 0, c: 0,
d: scaleFactorY, d: scaleFactorY,
e: 0, e: 0,
f: 0, f: 0,
}), })
); );
} }
rotate(angle: number): SVGMatrix { rotate(angle: number): SVGMatrix {
const cos = Math.cos(deg2rad * angle); const cos = Math.cos(deg2rad * angle);
const sin = Math.sin(deg2rad * angle); const sin = Math.sin(deg2rad * angle);
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { a: cos, b: sin, c: -sin, d: cos, e: 0, f: 0 }), multiplyMatrices(this, { a: cos, b: sin, c: -sin, d: cos, e: 0, f: 0 })
); );
} }
rotateFromVector(x: number, y: number): SVGMatrix { rotateFromVector(x: number, y: number): SVGMatrix {
const angle = Math.atan2(y, x); const angle = Math.atan2(y, x);
const cos = Math.cos(deg2rad * angle); const cos = Math.cos(deg2rad * angle);
const sin = Math.sin(deg2rad * angle); const sin = Math.sin(deg2rad * angle);
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { a: cos, b: sin, c: -sin, d: cos, e: 0, f: 0 }), multiplyMatrices(this, { a: cos, b: sin, c: -sin, d: cos, e: 0, f: 0 })
); );
} }
flipX(): SVGMatrix { flipX(): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { a: -1, b: 0, c: 0, d: 1, e: 0, f: 0 }), multiplyMatrices(this, { a: -1, b: 0, c: 0, d: 1, e: 0, f: 0 })
); );
} }
flipY(): SVGMatrix { flipY(): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { a: 1, b: 0, c: 0, d: -1, e: 0, f: 0 }), multiplyMatrices(this, { a: 1, b: 0, c: 0, d: -1, e: 0, f: 0 })
); );
} }
skewX(angle: number): SVGMatrix { skewX(angle: number): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { multiplyMatrices(this, {
a: 1, a: 1,
b: 0, b: 0,
c: Math.tan(deg2rad * angle), c: Math.tan(deg2rad * angle),
d: 1, d: 1,
e: 0, e: 0,
f: 0, f: 0,
}), })
); );
} }
skewY(angle: number): SVGMatrix { skewY(angle: number): SVGMatrix {
return new SVGMatrix( return new SVGMatrix(
multiply_matrices(this, { multiplyMatrices(this, {
a: 1, a: 1,
b: Math.tan(deg2rad * angle), b: Math.tan(deg2rad * angle),
c: 0, c: 0,
d: 1, d: 1,
e: 0, e: 0,
f: 0, f: 0,
}), })
); );
} }
} }
@@ -218,6 +228,7 @@ export class SVGPoint implements SVGPoint {
this.y = 0; this.y = 0;
} }
} }
matrixTransform(matrix: Matrix): SVGPoint { matrixTransform(matrix: Matrix): SVGPoint {
return new SVGPoint(matrixTransform(matrix, this)); return new SVGPoint(matrixTransform(matrix, this));
} }
@@ -239,20 +250,23 @@ export default class Shape<P> extends Component<P> {
super(props); super(props);
SvgTouchableMixin(this); SvgTouchableMixin(this);
} }
refMethod: (instance: (Shape<P> & NativeMethods) | null) => void = ( refMethod: (instance: (Shape<P> & NativeMethods) | null) => void = (
instance: (Shape<P> & NativeMethods) | null, instance: (Shape<P> & NativeMethods) | null
) => { ) => {
this.root = instance; this.root = instance;
}; };
// Hack to make Animated work with Shape components. // Hack to make Animated work with Shape components.
getNativeScrollRef(): (Shape<P> & NativeMethods) | null { getNativeScrollRef(): (Shape<P> & NativeMethods) | null {
return this.root; return this.root;
} }
setNativeProps = ( setNativeProps = (
props: P & { props: P & {
matrix?: ColumnMajorTransformMatrix; matrix?: ColumnMajorTransformMatrix;
fill?: ColorValue; fill?: ColorValue;
} & TransformProps, } & TransformProps
) => { ) => {
if (props.fill) { if (props.fill) {
// @ts-ignore TODO: native `fill` prop differs from the one passed in props // @ts-ignore TODO: native `fill` prop differs from the one passed in props
@@ -260,6 +274,7 @@ export default class Shape<P> extends Component<P> {
} }
this.root?.setNativeProps(props); this.root?.setNativeProps(props);
}; };
/* /*
* The following native methods are experimental and likely broken in some * The following native methods are experimental and likely broken in some
* ways. If you have a use case for these, please open an issue with a * ways. If you have a use case for these, please open an issue with a
@@ -282,42 +297,48 @@ export default class Shape<P> extends Component<P> {
clipped, clipped,
}); });
}; };
getCTM = (): SVGMatrix => { getCTM = (): SVGMatrix => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return new SVGMatrix(RNSVGRenderableModule.getCTM(handle)); return new SVGMatrix(RNSVGRenderableModule.getCTM(handle));
}; };
getScreenCTM = (): SVGMatrix => { getScreenCTM = (): SVGMatrix => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return new SVGMatrix(RNSVGRenderableModule.getScreenCTM(handle)); return new SVGMatrix(RNSVGRenderableModule.getScreenCTM(handle));
}; };
isPointInFill = (options: DOMPointInit): boolean | undefined => { isPointInFill = (options: DOMPointInit): boolean | undefined => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return RNSVGRenderableModule.isPointInFill(handle, options); return RNSVGRenderableModule.isPointInFill(handle, options);
}; };
isPointInStroke = (options: DOMPointInit): boolean | undefined => { isPointInStroke = (options: DOMPointInit): boolean | undefined => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return RNSVGRenderableModule.isPointInStroke(handle, options); return RNSVGRenderableModule.isPointInStroke(handle, options);
}; };
getTotalLength = (): number | undefined => { getTotalLength = (): number | undefined => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return RNSVGRenderableModule.getTotalLength(handle); return RNSVGRenderableModule.getTotalLength(handle);
}; };
getPointAtLength = (length: number): SVGPoint => { getPointAtLength = (length: number): SVGPoint => {
const handle = findNodeHandle(this.root); const handle = findNodeHandle(this.root);
const RNSVGRenderableModule: Spec = const RNSVGRenderableModule: Spec =
require('../fabric/NativeSvgRenderableModule').default; require('../fabric/NativeSvgRenderableModule').default;
return new SVGPoint( return new SVGPoint(
RNSVGRenderableModule.getPointAtLength(handle, { length }), RNSVGRenderableModule.getPointAtLength(handle, { length })
); );
}; };
} }

View File

@@ -9,7 +9,7 @@ export interface StopProps {
parent?: Component; parent?: Component;
} }
export default class Stop extends Component<StopProps, {}> { export default class Stop extends Component<StopProps> {
static displayName = 'Stop'; static displayName = 'Stop';
setNativeProps = () => { setNativeProps = () => {

View File

@@ -1,5 +1,5 @@
import type { Component } from 'react'; import type { Component } from 'react';
import React from 'react'; import * as React from 'react';
import type { import type {
ColorValue, ColorValue,
MeasureInWindowOnSuccessCallback, MeasureInWindowOnSuccessCallback,
@@ -62,7 +62,7 @@ export default class Svg extends Shape<SvgProps> {
measureLayout = ( measureLayout = (
relativeToNativeNode: number, relativeToNativeNode: number,
onSuccess: MeasureLayoutOnSuccessCallback, onSuccess: MeasureLayoutOnSuccessCallback,
onFail: () => void /* currently unused */, onFail: () => void /* currently unused */
) => { ) => {
const { root } = this; const { root } = this;
root && root.measureLayout(relativeToNativeNode, onSuccess, onFail); root && root.measureLayout(relativeToNativeNode, onSuccess, onFail);
@@ -72,7 +72,7 @@ export default class Svg extends Shape<SvgProps> {
props: SvgProps & { props: SvgProps & {
bbWidth?: NumberProp; bbWidth?: NumberProp;
bbHeight?: NumberProp; bbHeight?: NumberProp;
}, }
) => { ) => {
const { width, height } = props; const { width, height } = props;
if (width) { if (width) {
@@ -85,12 +85,13 @@ export default class Svg extends Shape<SvgProps> {
root && root.setNativeProps(props); root && root.setNativeProps(props);
}; };
toDataURL = (callback: (base64: string) => void, options?: Object) => { toDataURL = (callback: (base64: string) => void, options?: object) => {
if (!callback) { if (!callback) {
return; return;
} }
const handle = findNodeHandle(this.root as Component); const handle = findNodeHandle(this.root as Component);
const RNSVGSvgViewModule: Spec = const RNSVGSvgViewModule: Spec =
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('../fabric/NativeSvgViewModule').default; require('../fabric/NativeSvgViewModule').default;
RNSVGSvgViewModule.toDataURL(handle, options, callback); RNSVGSvgViewModule.toDataURL(handle, options, callback);
}; };
@@ -201,8 +202,7 @@ export default class Svg extends Shape<SvgProps> {
<RNSVGSvg <RNSVGSvg
{...props} {...props}
ref={(ref) => this.refMethod(ref as (Svg & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (Svg & NativeMethods) | null)}
{...extractViewBox({ viewBox, preserveAspectRatio })} {...extractViewBox({ viewBox, preserveAspectRatio })}>
>
<G <G
{...{ {...{
children, children,

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import extractViewBox from '../lib/extract/extractViewBox'; import extractViewBox from '../lib/extract/extractViewBox';
import Shape from './Shape'; import Shape from './Shape';
import RNSVGSymbol from '../fabric/SymbolNativeComponent'; import RNSVGSymbol from '../fabric/SymbolNativeComponent';
@@ -23,10 +23,9 @@ export default class Symbol extends Shape<SymbolProps> {
const symbolProps = { name: id }; const symbolProps = { name: id };
return ( return (
<RNSVGSymbol <RNSVGSymbol
ref={(ref) => this.refMethod(ref as (Symbol & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as Shape<SymbolProps> & NativeMethods)}
{...symbolProps} {...symbolProps}
{...extractViewBox(props)} {...extractViewBox(props)}>
>
{children} {children}
</RNSVGSymbol> </RNSVGSymbol>
); );

View File

@@ -1,5 +1,5 @@
import type { Component } from 'react'; import type { Component } from 'react';
import React from 'react'; import * as React from 'react';
import extractProps, { propsAndStyles } from '../lib/extract/extractProps'; import extractProps, { propsAndStyles } from '../lib/extract/extractProps';
import extractTransform from '../lib/extract/extractTransform'; import extractTransform from '../lib/extract/extractTransform';
import type { TextChild } from '../lib/extract/extractText'; import type { TextChild } from '../lib/extract/extractText';
@@ -31,8 +31,8 @@ export default class TSpan extends Shape<TSpanProps> {
setNativeProps = ( setNativeProps = (
props: TSpanProps & { props: TSpanProps & {
matrix?: ColumnMajorTransformMatrix; matrix?: ColumnMajorTransformMatrix;
style?: [] | {}; style?: [] | unknown;
}, }
) => { ) => {
const matrix = !props.matrix && extractTransform(props); const matrix = !props.matrix && extractTransform(props);
if (matrix) { if (matrix) {
@@ -51,7 +51,7 @@ export default class TSpan extends Shape<TSpanProps> {
x: null, x: null,
y: null, y: null,
}, },
this, this
); );
Object.assign(props, extractText(prop, false)); Object.assign(props, extractText(prop, false));
props.ref = this.refMethod as (instance: Component | null) => void; props.ref = this.refMethod as (instance: Component | null) => void;

View File

@@ -1,5 +1,5 @@
import type { Component, ReactNode } from 'react'; import type { Component, ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import extractText from '../lib/extract/extractText'; import extractText from '../lib/extract/extractText';
import extractProps, { propsAndStyles } from '../lib/extract/extractProps'; import extractProps, { propsAndStyles } from '../lib/extract/extractProps';
import extractTransform from '../lib/extract/extractTransform'; import extractTransform from '../lib/extract/extractTransform';
@@ -31,8 +31,8 @@ export default class Text extends Shape<TextProps> {
setNativeProps = ( setNativeProps = (
props: TextProps & { props: TextProps & {
matrix?: ColumnMajorTransformMatrix; matrix?: ColumnMajorTransformMatrix;
style?: [] | {}; style?: [] | unknown;
}, }
) => { ) => {
const matrix = props && !props.matrix && extractTransform(props); const matrix = props && !props.matrix && extractTransform(props);
if (matrix) { if (matrix) {
@@ -51,7 +51,7 @@ export default class Text extends Shape<TextProps> {
x: null, x: null,
y: null, y: null,
}, },
this, this
); );
Object.assign(props, extractText(prop, true)); Object.assign(props, extractText(prop, true));
props.ref = this.refMethod as (instance: Component | null) => void; props.ref = this.refMethod as (instance: Component | null) => void;

View File

@@ -1,5 +1,5 @@
import type { Component } from 'react'; import type { Component } from 'react';
import React from 'react'; import * as React from 'react';
import extractTransform from '../lib/extract/extractTransform'; import extractTransform from '../lib/extract/extractTransform';
import { withoutXY } from '../lib/extract/extractProps'; import { withoutXY } from '../lib/extract/extractProps';
import type { import type {
@@ -33,10 +33,10 @@ export default class TextPath extends Shape<TextPathProps> {
static displayName = 'TextPath'; static displayName = 'TextPath';
setNativeProps = ( setNativeProps = (
props: Object & { props: object & {
matrix?: ColumnMajorTransformMatrix; matrix?: ColumnMajorTransformMatrix;
style?: [] | {}; style?: [] | unknown;
} & TransformProps, } & TransformProps
) => { ) => {
const matrix = !props.matrix && extractTransform(props); const matrix = !props.matrix && extractTransform(props);
if (matrix) { if (matrix) {
@@ -69,7 +69,7 @@ export default class TextPath extends Shape<TextPathProps> {
{ {
children, children,
}, },
true, true
), ),
{ {
href: match, href: match,
@@ -79,7 +79,7 @@ export default class TextPath extends Shape<TextPathProps> {
side, side,
alignmentBaseline, alignmentBaseline,
midLine, midLine,
}, }
); );
props.ref = this.refMethod as (instance: Component | null) => void; props.ref = this.refMethod as (instance: Component | null) => void;
return <RNSVGTextPath {...props} />; return <RNSVGTextPath {...props} />;
@@ -88,7 +88,7 @@ export default class TextPath extends Shape<TextPathProps> {
console.warn( console.warn(
'Invalid `href` prop for `TextPath` element, expected a href like "#id", but got: "' + 'Invalid `href` prop for `TextPath` element, expected a href like "#id", but got: "' +
href + href +
'"', '"'
); );
return ( return (
<TSpan ref={this.refMethod as (instance: Component | null) => void}> <TSpan ref={this.refMethod as (instance: Component | null) => void}>

View File

@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import React from 'react'; import * as React from 'react';
import { import {
stringifyPropsForFabric, stringifyPropsForFabric,
withoutXY, withoutXY,
@@ -50,7 +50,7 @@ export default class Use extends Shape<UseProps> {
console.warn( console.warn(
'Invalid `href` prop for `Use` element, expected a href like "#id", but got: "' + 'Invalid `href` prop for `Use` element, expected a href like "#id", but got: "' +
href + href +
'"', '"'
); );
} }
const useProps = stringifyPropsForFabric({ const useProps = stringifyPropsForFabric({
@@ -64,8 +64,7 @@ export default class Use extends Shape<UseProps> {
<RNSVGUse <RNSVGUse
ref={(ref) => this.refMethod(ref as (Use & NativeMethods) | null)} ref={(ref) => this.refMethod(ref as (Use & NativeMethods) | null)}
{...withoutXY(this, props)} {...withoutXY(this, props)}
{...useProps} {...useProps}>
>
{children} {children}
</RNSVGUse> </RNSVGUse>
); );

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/ban-types */
// its needed for codegen to work
import type { TurboModule } from 'react-native'; import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native'; import { TurboModuleRegistry } from 'react-native';
import type { Int32, Float } from 'react-native/Libraries/Types/CodegenTypes'; import type { Int32, Float } from 'react-native/Libraries/Types/CodegenTypes';

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/ban-types */
// its needed for codegen to work
import type { TurboModule } from 'react-native'; import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native'; import { TurboModuleRegistry } from 'react-native';
import type { Int32 } from 'react-native/Libraries/Types/CodegenTypes'; import type { Int32 } from 'react-native/Libraries/Types/CodegenTypes';
@@ -6,7 +8,7 @@ export interface Spec extends TurboModule {
toDataURL( toDataURL(
tag: Int32 | null, tag: Int32 | null,
options?: Object, options?: Object,
callback?: (base64: string) => void, callback?: (base64: string) => void
): void; ): void;
} }

View File

@@ -1,5 +1,5 @@
import type { ViewProps as VP } from 'react-native'; import type { ViewProps as VP } from 'react-native';
interface ViewProps extends Omit<VP, 'pointerEvents'> {} type ViewProps = Omit<VP, 'pointerEvents'>;
export type { ViewProps }; export type { ViewProps };

View File

@@ -1,531 +0,0 @@
/**
* Flowtype definitions for index
* Generated by Flowgen from a Typescript Definition
* Flowgen v1.17.0
*/
import * as React from "react";
import * as ReactNative from "react-native";
import {
ColorValue,
GestureResponderEvent,
LayoutChangeEvent,
TransformsStyle,
} from "react-native";
export type NumberProp = string | number;
export type NumberArray = NumberProp[] | NumberProp;
export type FillRule = "evenodd" | "nonzero";
export type Units = "userSpaceOnUse" | "objectBoundingBox";
export type MarkerUnits = "strokeWidth" | "userSpaceOnUse";
export type Orient = "auto" | "auto-start-reverse";
export type TextAnchor = "start" | "middle" | "end";
export type FontStyle = "normal" | "italic" | "oblique";
export type FontVariant = "normal" | "small-caps";
export type FontWeight =
| NumberProp
| "normal"
| "bold"
| "bolder"
| "lighter"
| "100"
| "200"
| "300"
| "400"
| "500"
| "600"
| "700"
| "800"
| "900";
export type FontStretch =
| "normal"
| "wider"
| "narrower"
| "ultra-condensed"
| "extra-condensed"
| "condensed"
| "semi-condensed"
| "semi-expanded"
| "expanded"
| "extra-expanded"
| "ultra-expanded";
export type TextDecoration =
| "none"
| "underline"
| "overline"
| "line-through"
| "blink";
export type FontVariantLigatures = "normal" | "none";
export type AlignmentBaseline =
| "baseline"
| "text-bottom"
| "alphabetic"
| "ideographic"
| "middle"
| "central"
| "mathematical"
| "text-top"
| "bottom"
| "center"
| "top"
| "text-before-edge"
| "text-after-edge"
| "before-edge"
| "after-edge"
| "hanging";
export type BaselineShift =
| "sub"
| "super"
| "baseline"
| $ReadOnlyArray<NumberProp>
| NumberProp;
export type LengthAdjust = "spacing" | "spacingAndGlyphs";
export type TextPathMethod = "align" | "stretch";
export type TextPathSpacing = "auto" | "exact";
export type TextPathMidLine = "sharp" | "smooth";
export type Linecap = "butt" | "square" | "round";
export type Linejoin = "miter" | "bevel" | "round";
export interface TouchableProps {
disabled?: boolean;
onPress?: (event: GestureResponderEvent) => void;
onPressIn?: (event: GestureResponderEvent) => void;
onPressOut?: (event: GestureResponderEvent) => void;
onLongPress?: (event: GestureResponderEvent) => void;
delayPressIn?: number;
delayPressOut?: number;
delayLongPress?: number;
}
export type ResponderProps = {
pointerEvents?: "box-none" | "none" | "box-only" | "auto",
...
} & ReactNative.GestureResponderHandlers;
export type Color = ColorValue;
export interface FillProps {
fill?: Color;
fillOpacity?: NumberProp;
fillRule?: FillRule;
}
export interface ClipProps {
clipRule?: FillRule;
clipPath?: string;
}
export interface VectorEffectProps {
vectorEffect?:
| "none"
| "non-scaling-stroke"
| "nonScalingStroke"
| "default"
| "inherit"
| "uri";
}
export interface DefinitionProps {
id?: string;
}
export interface StrokeProps {
stroke?: Color;
strokeWidth?: NumberProp;
strokeOpacity?: NumberProp;
strokeDasharray?: $ReadOnlyArray<NumberProp> | NumberProp;
strokeDashoffset?: NumberProp;
strokeLinecap?: Linecap;
strokeLinejoin?: Linejoin;
strokeMiterlimit?: NumberProp;
}
export interface FontObject {
fontStyle?: FontStyle;
fontVariant?: FontVariant;
fontWeight?: FontWeight;
fontStretch?: FontStretch;
fontSize?: NumberProp;
fontFamily?: string;
textAnchor?: TextAnchor;
textDecoration?: TextDecoration;
letterSpacing?: NumberProp;
wordSpacing?: NumberProp;
kerning?: NumberProp;
fontFeatureSettings?: string;
fontVariantLigatures?: FontVariantLigatures;
fontVariationSettings?: string;
}
export type FontProps = {
font?: FontObject,
...
} & FontObject;
export interface TransformObject {
translate?: NumberArray;
translateX?: NumberProp;
translateY?: NumberProp;
origin?: NumberArray;
originX?: NumberProp;
originY?: NumberProp;
scale?: NumberArray;
scaleX?: NumberProp;
scaleY?: NumberProp;
skew?: NumberArray;
skewX?: NumberProp;
skewY?: NumberProp;
rotation?: NumberProp;
x?: NumberArray;
y?: NumberArray;
}
export type ColumnMajorTransformMatrix = [
number,
number,
number,
number,
number,
number
];
export type TransformProps = {
transform?:
| ColumnMajorTransformMatrix
| string
| TransformObject
| $PropertyType<TransformsStyle, "transform">,
...
} & TransformObject;
export interface CommonMaskProps {
mask?: string;
}
export interface CommonMarkerProps {
marker?: string;
markerStart?: string;
markerMid?: string;
markerEnd?: string;
}
export interface NativeProps {
onLayout?: (event: LayoutChangeEvent) => void;
}
export type CommonPathProps = { ... } & FillProps &
StrokeProps &
ClipProps &
TransformProps &
VectorEffectProps &
ResponderProps &
TouchableProps &
DefinitionProps &
CommonMarkerProps &
CommonMaskProps &
NativeProps;
export type CircleProps = {
cx?: NumberProp,
cy?: NumberProp,
opacity?: NumberProp,
r?: NumberProp,
...
} & CommonPathProps;
declare export var Circle: React.ComponentClass<CircleProps>;
export type CircleType = React.ComponentClass<CircleProps>;
export interface ClipPathProps {
id?: string;
}
declare export var ClipPath: React.ComponentClass<ClipPathProps>;
export type ClipPathType = React.ComponentClass<ClipPathProps>;
declare export var Defs: React.ComponentClass<{ ... }>;
export type DefsType = React.ComponentClass<{ ... }>;
export type EllipseProps = {
cx?: NumberProp,
cy?: NumberProp,
opacity?: NumberProp,
rx?: NumberProp,
ry?: NumberProp,
...
} & CommonPathProps;
declare export var Ellipse: React.ComponentClass<EllipseProps>;
export type EllipseType = React.ComponentClass<EllipseProps>;
export type GProps = {
opacity?: NumberProp,
...
} & CommonPathProps &
FontProps;
declare export var G: React.ComponentClass<GProps>;
export type GType = React.ComponentClass<GProps>;
export interface ForeignObjectProps {
x?: NumberProp;
y?: NumberProp;
width?: NumberProp;
height?: NumberProp;
}
declare export var ForeignObject: React.ComponentClass<ForeignObjectProps>;
export type ForeignObjectType = React.ComponentClass<ForeignObjectProps>;
export type ImageProps = {
x?: NumberProp,
y?: NumberProp,
width?: NumberProp,
height?: NumberProp,
xlinkHref?: $PropertyType<ReactNative.ImageProps, "source"> | string,
href?: $PropertyType<ReactNative.ImageProps, "source"> | string,
preserveAspectRatio?: string,
opacity?: NumberProp,
clipPath?: string,
id?: string,
...
} & ResponderProps &
CommonMaskProps &
ClipProps &
TouchableProps;
declare export var Image: React.ComponentClass<ImageProps>;
export type ImageType = React.ComponentClass<ImageProps>;
export type LineProps = {
opacity?: NumberProp,
x1?: NumberProp,
x2?: NumberProp,
y1?: NumberProp,
y2?: NumberProp,
...
} & CommonPathProps;
declare export var Line: React.ComponentClass<LineProps>;
export type LineType = React.ComponentClass<LineProps>;
export interface LinearGradientProps {
x1?: NumberProp;
x2?: NumberProp;
y1?: NumberProp;
y2?: NumberProp;
gradientUnits?: Units;
gradientTransform?: ColumnMajorTransformMatrix | string;
id?: string;
}
declare export var LinearGradient: React.ComponentClass<LinearGradientProps>;
export type LinearGradientType = React.ComponentClass<LinearGradientProps>;
export type PathProps = {
d?: string,
opacity?: NumberProp,
...
} & CommonPathProps;
declare export var Path: React.ComponentClass<PathProps>;
export type PathType = React.ComponentClass<PathProps>;
export interface PatternProps {
id?: string;
x?: NumberProp;
y?: NumberProp;
width?: NumberProp;
height?: NumberProp;
patternTransform?: ColumnMajorTransformMatrix | string;
patternUnits?: Units;
patternContentUnits?: Units;
viewBox?: string;
preserveAspectRatio?: string;
}
declare export var Pattern: React.ComponentClass<PatternProps>;
export type PatternType = React.ComponentClass<PatternProps>;
export type PolygonProps = {
opacity?: NumberProp,
points?: string | $ReadOnlyArray<NumberProp>,
...
} & CommonPathProps;
declare export var Polygon: React.ComponentClass<PolygonProps>;
export type PolygonType = React.ComponentClass<PolygonProps>;
export type PolylineProps = {
opacity?: NumberProp,
points?: string | $ReadOnlyArray<NumberProp>,
...
} & CommonPathProps;
declare export var Polyline: React.ComponentClass<PolylineProps>;
export type PolylineType = React.ComponentClass<PolylineProps>;
export interface RadialGradientProps {
fx?: NumberProp;
fy?: NumberProp;
rx?: NumberProp;
ry?: NumberProp;
cx?: NumberProp;
cy?: NumberProp;
r?: NumberProp;
gradientUnits?: Units;
gradientTransform?: ColumnMajorTransformMatrix | string;
id?: string;
}
declare export var RadialGradient: React.ComponentClass<RadialGradientProps>;
export type RadialGradientType = React.ComponentClass<RadialGradientProps>;
export type RectProps = {
x?: NumberProp,
y?: NumberProp,
width?: NumberProp,
height?: NumberProp,
rx?: NumberProp,
ry?: NumberProp,
opacity?: NumberProp,
...
} & CommonPathProps;
declare export var Rect: React.ComponentClass<RectProps>;
export type RectType = React.ComponentClass<RectProps>;
export interface StopProps {
stopColor?: Color;
stopOpacity?: NumberProp;
offset?: NumberProp;
}
declare export var Stop: React.ComponentClass<StopProps>;
export type StopType = React.ComponentClass<StopProps>;
export type SvgProps = {
width?: NumberProp,
height?: NumberProp,
viewBox?: string,
preserveAspectRatio?: string,
color?: Color,
title?: string,
...
} & GProps &
ReactNative.ViewProperties;
declare export var Svg: React.ComponentClass<SvgProps>;
export type SvgType = React.ComponentClass<SvgProps>;
declare export default typeof Svg;
export interface SymbolProps {
id?: string;
viewBox?: string;
preserveAspectRatio?: string;
opacity?: NumberProp;
}
declare export var Symbol: React.ComponentClass<SymbolProps>;
export type SymbolType = React.ComponentClass<SymbolProps>;
export type TSpanProps = {
x?: NumberArray,
y?: NumberArray,
dx?: NumberArray,
dy?: NumberArray,
rotate?: NumberArray,
inlineSize?: NumberProp,
...
} & CommonPathProps &
FontProps;
declare export var TSpan: React.ComponentClass<TSpanProps>;
export type TSpanType = React.ComponentClass<TSpanProps>;
export type TextSpecificProps = {
alignmentBaseline?: AlignmentBaseline,
baselineShift?: BaselineShift,
verticalAlign?: NumberProp,
lengthAdjust?: LengthAdjust,
textLength?: NumberProp,
fontData?: null | {
[name: string]: mixed,
...
},
fontFeatureSettings?: string,
...
} & CommonPathProps &
FontProps;
export type TextProps = {
x?: NumberArray,
y?: NumberArray,
dx?: NumberArray,
dy?: NumberArray,
rotate?: NumberArray,
opacity?: NumberProp,
inlineSize?: NumberProp,
...
} & TextSpecificProps;
declare export var Text: React.ComponentClass<TextProps>;
export type TextType = React.ComponentClass<TextProps>;
export type TextPathProps = {
xlinkHref?: string,
href?: string,
startOffset?: NumberProp,
method?: TextPathMethod,
spacing?: TextPathSpacing,
midLine?: TextPathMidLine,
...
} & TextSpecificProps;
declare export var TextPath: React.ComponentClass<TextPathProps>;
export type TextPathType = React.ComponentClass<TextPathProps>;
export type UseProps = {
xlinkHref?: string,
href?: string,
width?: NumberProp,
height?: NumberProp,
x?: NumberProp,
y?: NumberProp,
opacity?: NumberProp,
...
} & CommonPathProps;
declare export var Use: React.ComponentClass<UseProps>;
export type UseType = React.ComponentClass<UseProps>;
export type MaskProps = {
id?: string,
x?: NumberProp,
y?: NumberProp,
width?: NumberProp,
height?: NumberProp,
maskUnits?: Units,
maskContentUnits?: Units,
...
} & CommonPathProps;
declare export var Mask: React.ComponentClass<MaskProps>;
export type MaskType = React.ComponentClass<MaskProps>;
export interface MarkerProps {
id?: string;
viewBox?: string;
preserveAspectRatio?: string;
refX?: NumberProp;
refY?: NumberProp;
markerWidth?: NumberProp;
markerHeight?: NumberProp;
markerUnits?: MarkerUnits;
orient?: Orient | NumberProp;
}
declare export var Marker: React.ComponentClass<MarkerProps>;
export type MarkerType = React.ComponentClass<MarkerProps>;
export type Styles = {
[property: string]: string,
...
};
export interface AST {
tag: string;
style?: Styles;
styles?: string;
priority?: Map<string, boolean | void>;
parent: AST | null;
children: (AST | string)[] | (React$Node | string)[];
props: {
[prop: string]: Styles | string | void,
...
};
Tag: React.ComponentType<>;
}
export type XmlAST = {
children: (XmlAST | string)[],
parent: XmlAST | null,
...
} & AST;
export type JsxAST = {
children: (React$Node | string)[],
...
} & AST;
export type UriProps = {
uri: string | null,
onError?: (error: Error) => void,
override?: SvgProps,
onError?: (error: Error) => void,
onLoad?: () => void,
...
} & SvgProps;
export type UriState = {
xml: string | null,
...
};
export type XmlProps = {
xml: string | null,
onError?: (error: Error) => void,
override?: SvgProps,
...
} & SvgProps;
export type XmlState = {
ast: JsxAST | null,
...
};
export type AstProps = {
ast: JsxAST | null,
override?: SvgProps,
...
} & SvgProps;
export type Middleware = (ast: XmlAST) => XmlAST;
declare export function parse(
source: string,
middleware?: Middleware
): JsxAST | null;
declare export var SvgAst: React.FunctionComponent<AstProps>;
declare export var SvgXml: React.FunctionComponent<XmlProps>;
declare export var SvgFromXml: React.ComponentClass<XmlProps, XmlState>;
declare export var SvgUri: React.FunctionComponent<UriProps>;
declare export var SvgFromUri: React.ComponentClass<UriProps, UriState>;
declare export var SvgCss: React.FunctionComponent<XmlProps>;
declare export var SvgWithCss: React.ComponentClass<XmlProps, XmlState>;
declare export var SvgCssUri: React.FunctionComponent<UriProps>;
declare export var SvgWithCssUri: React.ComponentClass<UriProps, UriState>;
declare export var inlineStyles: Middleware;

View File

@@ -70,7 +70,7 @@ export function append(
c2: number, c2: number,
d2: number, d2: number,
tx2: number, tx2: number,
ty2: number, ty2: number
) { ) {
const change = a2 !== 1 || b2 !== 0 || c2 !== 0 || d2 !== 1; const change = a2 !== 1 || b2 !== 0 || c2 !== 0 || d2 !== 1;
const translate = tx2 !== 0 || ty2 !== 0; const translate = tx2 !== 0 || ty2 !== 0;
@@ -131,7 +131,7 @@ export function appendTransform(
skewX: number, skewX: number,
skewY: number, skewY: number,
regX: number, regX: number,
regY: number, regY: number
) { ) {
if ( if (
x === 0 && x === 0 &&

View File

@@ -1,8 +1,7 @@
// @ts-ignore
import type { GestureResponderEvent } from 'react-native'; import type { GestureResponderEvent } from 'react-native';
import { Touchable } from 'react-native'; import { Touchable } from 'react-native';
const PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 }; const PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 };
// @ts-ignore // @ts-expect-error: Mixin is not typed
const { Mixin } = Touchable; const { Mixin } = Touchable;
const { const {
touchableHandleStartShouldSetResponder, touchableHandleStartShouldSetResponder,

View File

@@ -1,5 +1,6 @@
import type { ReactElement } from 'react'; import type { ReactElement } from 'react';
import React, { Children } from 'react'; import * as React from 'react';
import { Children } from 'react';
import { processColor } from 'react-native'; import { processColor } from 'react-native';
import extractOpacity from './extractOpacity'; import extractOpacity from './extractOpacity';
@@ -15,7 +16,7 @@ function percentToFloat(
| string | string
| { | {
__getAnimatedValue: () => number; __getAnimatedValue: () => number;
}, }
): number { ): number {
if (typeof percent === 'number') { if (typeof percent === 'number') {
return percent; return percent;
@@ -46,7 +47,7 @@ export default function extractGradient(
gradientTransform?: TransformProps['transform']; gradientTransform?: TransformProps['transform'];
gradientUnits?: 'objectBoundingBox' | 'userSpaceOnUse'; gradientUnits?: 'objectBoundingBox' | 'userSpaceOnUse';
} & TransformProps, } & TransformProps,
parent: {}, parent: unknown
) { ) {
const { id, children, gradientTransform, transform, gradientUnits } = props; const { id, children, gradientTransform, transform, gradientUnits } = props;
if (!id) { if (!id) {
@@ -58,7 +59,7 @@ export default function extractGradient(
? Children.map(children, (child) => ? Children.map(children, (child) =>
React.cloneElement(child, { React.cloneElement(child, {
parent, parent,
}), })
) )
: []; : [];
const l = childArray.length; const l = childArray.length;
@@ -75,7 +76,7 @@ export default function extractGradient(
const color = stopColor && processColor(stopColor); const color = stopColor && processColor(stopColor);
if (typeof color !== 'number' || isNaN(offsetNumber)) { if (typeof color !== 'number' || isNaN(offsetNumber)) {
console.warn( console.warn(
`"${stopColor}" is not a valid color or "${offset}" is not a valid offset`, `"${stopColor}" is not a valid color or "${offset}" is not a valid offset`
); );
continue; continue;
} }
@@ -97,7 +98,7 @@ export default function extractGradient(
children: childArray, children: childArray,
gradientUnits: (gradientUnits && units[gradientUnits]) || 0, gradientUnits: (gradientUnits && units[gradientUnits]) || 0,
gradientTransform: extractTransform( gradientTransform: extractTransform(
gradientTransform || transform || props, gradientTransform || transform || props
), ),
}; };
} }

View File

@@ -19,7 +19,7 @@ const clipRules: { evenodd: number; nonzero: number } = {
nonzero: 1, nonzero: 1,
}; };
export function propsAndStyles(props: Object & { style?: [] | {} }) { export function propsAndStyles(props: object & { style?: [] | unknown }) {
const { style } = props; const { style } = props;
return !style return !style
? props ? props
@@ -57,7 +57,7 @@ export default function extractProps(
StrokeProps & StrokeProps &
FillProps & FillProps &
ClipProps, ClipProps,
ref: Object, ref: object
) { ) {
const { const {
id, id,
@@ -140,7 +140,7 @@ export default function extractProps(
console.warn( console.warn(
'Invalid `clipPath` prop, expected a clipPath like "#id", but got: "' + 'Invalid `clipPath` prop, expected a clipPath like "#id", but got: "' +
clipPath + clipPath +
'"', '"'
); );
} }
} }
@@ -154,7 +154,7 @@ export default function extractProps(
console.warn( console.warn(
'Invalid `mask` prop, expected a mask like "#id", but got: "' + 'Invalid `mask` prop, expected a mask like "#id", but got: "' +
mask + mask +
'"', '"'
); );
} }
} }
@@ -162,7 +162,10 @@ export default function extractProps(
return extracted; return extracted;
} }
export function extract(instance: Object, props: Object & { style?: [] | {} }) { export function extract(
instance: object,
props: object & { style?: [] | unknown }
) {
return extractProps(propsAndStyles(props), instance); return extractProps(propsAndStyles(props), instance);
} }
@@ -180,8 +183,8 @@ export function stringifyPropsForFabric(props: {
} }
export function withoutXY( export function withoutXY(
instance: Object, instance: object,
props: Object & { style?: [] | {} }, props: object & { style?: [] | unknown }
) { ) {
return extractProps({ ...propsAndStyles(props), x: null, y: null }, instance); return extractProps({ ...propsAndStyles(props), x: null, y: null }, instance);
} }

View File

@@ -19,7 +19,7 @@ const clipRules: { evenodd: number; nonzero: number } = {
nonzero: 1, nonzero: 1,
}; };
export function propsAndStyles(props: Object & { style?: [] | {} }) { export function propsAndStyles(props: object & { style?: [] | unknown }) {
const { style } = props; const { style } = props;
return !style return !style
? props ? props
@@ -54,7 +54,7 @@ export default function extractProps(
StrokeProps & StrokeProps &
FillProps & FillProps &
ClipProps, ClipProps,
ref: Object, ref: object
) { ) {
const { const {
id, id,
@@ -122,7 +122,7 @@ export default function extractProps(
console.warn( console.warn(
'Invalid `clipPath` prop, expected a clipPath like "#id", but got: "' + 'Invalid `clipPath` prop, expected a clipPath like "#id", but got: "' +
clipPath + clipPath +
'"', '"'
); );
} }
} }
@@ -136,7 +136,7 @@ export default function extractProps(
console.warn( console.warn(
'Invalid `mask` prop, expected a mask like "#id", but got: "' + 'Invalid `mask` prop, expected a mask like "#id", but got: "' +
mask + mask +
'"', '"'
); );
} }
} }
@@ -144,7 +144,10 @@ export default function extractProps(
return extracted; return extracted;
} }
export function extract(instance: Object, props: Object & { style?: [] | {} }) { export function extract(
instance: object,
props: object & { style?: [] | unknown }
) {
return extractProps(propsAndStyles(props), instance); return extractProps(propsAndStyles(props), instance);
} }
@@ -166,8 +169,8 @@ export function stringifyPropsForFabric(props: {
} }
export function withoutXY( export function withoutXY(
instance: Object, instance: object,
props: Object & { style?: [] | {} }, props: object & { style?: [] | unknown }
) { ) {
return extractProps({ ...propsAndStyles(props), x: null, y: null }, instance); return extractProps({ ...propsAndStyles(props), x: null, y: null }, instance);
} }

View File

@@ -1,5 +1,6 @@
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import React, { Children } from 'react'; import * as React from 'react';
import { Children } from 'react';
import extractLengthList from './extractLengthList'; import extractLengthList from './extractLengthList';
import { pickNotNil } from '../util'; import { pickNotNil } from '../util';
import type { NumberArray, NumberProp } from './types'; import type { NumberArray, NumberProp } from './types';
@@ -33,7 +34,7 @@ function extractSingleFontFamily(fontFamilyString?: string) {
} }
function parseFontString(font: string) { function parseFontString(font: string) {
if (cachedFontObjectsFromString.hasOwnProperty(font)) { if (Object.prototype.hasOwnProperty.call(cachedFontObjectsFromString, font)) {
return cachedFontObjectsFromString[font]; return cachedFontObjectsFromString[font];
} }
const match = fontRegExp.exec(font); const match = fontRegExp.exec(font);
@@ -119,13 +120,13 @@ export function extractFont(props: fontProps) {
Object.keys(fontProps).map( Object.keys(fontProps).map(
(k) => (k) =>
(stringifiedFontProps[k] = (stringifiedFontProps[k] =
fontProps[k] === null ? null : String(fontProps[k])), fontProps[k] === null ? null : String(fontProps[k]))
); );
return stringifiedFontProps; return stringifiedFontProps;
} }
let TSpan: ComponentType<React.PropsWithChildren<{}>>; let TSpan: ComponentType<React.PropsWithChildren>;
export function setTSpan(TSpanImplementation: ComponentType) { export function setTSpan(TSpanImplementation: ComponentType) {
TSpan = TSpanImplementation; TSpan = TSpanImplementation;

View File

@@ -3,9 +3,9 @@ import type {
GestureResponderEvent, GestureResponderEvent,
GestureResponderHandlers, GestureResponderHandlers,
LayoutChangeEvent, LayoutChangeEvent,
TransformsStyle,
} from 'react-native'; } from 'react-native';
import type React from 'react'; import type React from 'react';
import type { TransformsStyle } from 'react-native';
export type NumberProp = string | number; export type NumberProp = string | number;
export type NumberArray = NumberProp[] | NumberProp; export type NumberArray = NumberProp[] | NumberProp;
@@ -262,10 +262,10 @@ export type ResponderInstanceProps = {
touchableHandleResponderRelease?: (e: GestureResponderEvent) => void; touchableHandleResponderRelease?: (e: GestureResponderEvent) => void;
touchableHandleResponderTerminate?: (e: GestureResponderEvent) => void; touchableHandleResponderTerminate?: (e: GestureResponderEvent) => void;
touchableHandleStartShouldSetResponder?: ( touchableHandleStartShouldSetResponder?: (
e: GestureResponderEvent, e: GestureResponderEvent
) => boolean; ) => boolean;
touchableHandleResponderTerminationRequest?: ( touchableHandleResponderTerminationRequest?: (
e: GestureResponderEvent, e: GestureResponderEvent
) => boolean; ) => boolean;
}; };

View File

@@ -3,7 +3,7 @@ import { StyleSheet } from 'react-native';
// Kept in separate file, to avoid name collision with Symbol element // Kept in separate file, to avoid name collision with Symbol element
export function resolve<T>( export function resolve<T>(
styleProp: Iterable<T> | undefined, styleProp: Iterable<T> | undefined,
cleanedProps: T, cleanedProps: T
) { ) {
if (styleProp) { if (styleProp) {
return StyleSheet return StyleSheet

View File

@@ -1,7 +1,7 @@
export function pickNotNil(object: { [prop: string]: unknown }) { export function pickNotNil(object: { [prop: string]: unknown }) {
const result: { [prop: string]: unknown } = {}; const result: { [prop: string]: unknown } = {};
for (const key in object) { for (const key in object) {
if (object.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(object, key)) {
const value = object[key]; const value = object[key];
if (value !== undefined && value !== null) { if (value !== undefined && value !== null) {
result[key] = value; result[key] = value;

View File

@@ -1,5 +1,6 @@
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import React, { Component, useEffect, useMemo, useState } from 'react'; import * as React from 'react';
import { Component, useEffect, useMemo, useState } from 'react';
import Rect from './elements/Rect'; import Rect from './elements/Rect';
import Circle from './elements/Circle'; import Circle from './elements/Circle';
import Ellipse from './elements/Ellipse'; import Ellipse from './elements/Ellipse';
@@ -65,7 +66,7 @@ export interface AST {
props: { props: {
[prop: string]: Styles | string | undefined; [prop: string]: Styles | string | undefined;
}; };
Tag: ComponentType<React.PropsWithChildren<{}>>; Tag: ComponentType<React.PropsWithChildren>;
} }
export interface XmlAST extends AST { export interface XmlAST extends AST {
@@ -79,7 +80,7 @@ export interface JsxAST extends AST {
export type AdditionalProps = { export type AdditionalProps = {
onError?: (error: Error) => void; onError?: (error: Error) => void;
override?: Object; override?: object;
onLoad?: () => void; onLoad?: () => void;
fallback?: JSX.Element; fallback?: JSX.Element;
}; };
@@ -112,7 +113,7 @@ export function SvgXml(props: XmlProps) {
try { try {
const ast = useMemo<JsxAST | null>( const ast = useMemo<JsxAST | null>(
() => (xml !== null ? parse(xml) : null), () => (xml !== null ? parse(xml) : null),
[xml], [xml]
); );
return <SvgAst ast={ast} override={override || props} />; return <SvgAst ast={ast} override={override || props} />;
} catch (error) { } catch (error) {
@@ -161,12 +162,14 @@ export class SvgFromXml extends Component<XmlProps, XmlState> {
componentDidMount() { componentDidMount() {
this.parse(this.props.xml); this.parse(this.props.xml);
} }
componentDidUpdate(prevProps: { xml: string | null }) { componentDidUpdate(prevProps: { xml: string | null }) {
const { xml } = this.props; const { xml } = this.props;
if (xml !== prevProps.xml) { if (xml !== prevProps.xml) {
this.parse(xml); this.parse(xml);
} }
} }
parse(xml: string | null) { parse(xml: string | null) {
try { try {
this.setState({ ast: xml ? parse(xml) : null }); this.setState({ ast: xml ? parse(xml) : null });
@@ -174,6 +177,7 @@ export class SvgFromXml extends Component<XmlProps, XmlState> {
console.error(e); console.error(e);
} }
} }
render() { render() {
const { const {
props, props,
@@ -188,12 +192,14 @@ export class SvgFromUri extends Component<UriProps, UriState> {
componentDidMount() { componentDidMount() {
this.fetch(this.props.uri); this.fetch(this.props.uri);
} }
componentDidUpdate(prevProps: { uri: string | null }) { componentDidUpdate(prevProps: { uri: string | null }) {
const { uri } = this.props; const { uri } = this.props;
if (uri !== prevProps.uri) { if (uri !== prevProps.uri) {
this.fetch(uri); this.fetch(uri);
} }
} }
async fetch(uri: string | null) { async fetch(uri: string | null) {
try { try {
this.setState({ xml: uri ? await fetchText(uri) : null }); this.setState({ xml: uri ? await fetchText(uri) : null });
@@ -201,6 +207,7 @@ export class SvgFromUri extends Component<UriProps, UriState> {
console.error(e); console.error(e);
} }
} }
render() { render() {
const { const {
props, props,
@@ -235,7 +242,7 @@ export function getStyle(string: string): Styles {
export function astToReact( export function astToReact(
value: AST | string, value: AST | string,
index: number, index: number
): JSX.Element | string { ): JSX.Element | string {
if (typeof value === 'object') { if (typeof value === 'object') {
const { Tag, props, children } = value; const { Tag, props, children } = value;
@@ -296,12 +303,12 @@ export function parse(source: string, middleware?: Middleware): JsxAST | null {
let state = metadata; let state = metadata;
let children = null; let children = null;
let root: XmlAST | undefined; let root: XmlAST | undefined;
let stack: XmlAST[] = []; const stack: XmlAST[] = [];
function error(message: string) { function error(message: string) {
const { line, column, snippet } = locate(source, i); const { line, column, snippet } = locate(source, i);
throw new Error( throw new Error(
`${message} (${line}:${column}). If this is valid SVG, it's probably a bug. Please raise an issue\n\n${snippet}`, `${message} (${line}:${column}). If this is valid SVG, it's probably a bug. Please raise an issue\n\n${snippet}`
); );
} }
@@ -435,7 +442,7 @@ export function parse(source: string, middleware?: Middleware): JsxAST | null {
if (currentElement && tag !== currentElement.tag) { if (currentElement && tag !== currentElement.tag) {
error( error(
`Expected closing tag </${tag}> to match opening tag <${currentElement.tag}>`, `Expected closing tag </${tag}> to match opening tag <${currentElement.tag}>`
); );
} }

View File

@@ -1,23 +1,19 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2017", "baseUrl": ".",
"lib": ["es6", "es2016"], "declaration": true,
"preserveSymlinks": true,
"target": "es6",
"module": "ESNext",
"jsx": "react-native", "jsx": "react-native",
"strict": true, "skipLibCheck": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"types": ["react", "react-native"] "moduleResolution": "node",
"lib": ["es6", "dom"],
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
}, },
"include": ["src/**/*"] "include": ["src"]
} }

4559
yarn.lock

File diff suppressed because it is too large Load Diff