Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-inlinesvg

Package Overview
Dependencies
Maintainers
1
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-inlinesvg - npm Package Compare versions

Comparing version 1.2.0 to 2.0.0

esm/helpers.d.ts

22

lib/helpers.d.ts

@@ -1,10 +0,12 @@

export declare const canUseDOM: () => boolean;
export declare const supportsInlineSVG: () => boolean | null;
export declare class InlineSVGError extends Error {
name: string;
message: string;
data?: object;
constructor(message: string, data?: object);
}
export declare const isSupportedEnvironment: () => boolean | null;
export declare const randomString: (length: number) => string;
export declare const STATUS: {
FAILED: string;
LOADED: string;
LOADING: string;
PENDING: string;
READY: string;
UNSUPPORTED: string;
};
export declare function canUseDOM(): boolean;
export declare function supportsInlineSVG(): boolean;
export declare function isSupportedEnvironment(): boolean;
export declare function randomString(length: number): string;
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.randomString = exports.isSupportedEnvironment = exports.supportsInlineSVG = exports.canUseDOM = exports.STATUS = void 0;
var exenv_1 = require("exenv");
exports.canUseDOM = function () { return exenv_1.canUseDOM; };
exports.supportsInlineSVG = function () {
exports.STATUS = {
FAILED: 'failed',
LOADED: 'loaded',
LOADING: 'loading',
PENDING: 'pending',
READY: 'ready',
UNSUPPORTED: 'unsupported',
};
function canUseDOM() {
return exenv_1.canUseDOM;
}
exports.canUseDOM = canUseDOM;
function supportsInlineSVG() {
/* istanbul ignore next */

@@ -25,21 +24,10 @@ if (!document) {

div.innerHTML = '<svg />';
return div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg';
};
// tslint:disable-next-line:no-shadowed-variable
var InlineSVGError = /** @class */ (function (_super) {
__extends(InlineSVGError, _super);
function InlineSVGError(message, data) {
var _this = _super.call(this) || this;
_this.name = 'InlineSVGError';
_this.message = message;
_this.data = data;
return _this;
}
return InlineSVGError;
}(Error));
exports.InlineSVGError = InlineSVGError;
exports.isSupportedEnvironment = function () {
return exports.supportsInlineSVG() && typeof window !== 'undefined' && window !== null;
};
exports.randomString = function (length) {
return !!div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg';
}
exports.supportsInlineSVG = supportsInlineSVG;
function isSupportedEnvironment() {
return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;
}
exports.isSupportedEnvironment = isSupportedEnvironment;
function randomString(length) {
var letters = 'abcdefghijklmnopqrstuvwxyz';

@@ -56,3 +44,4 @@ var numbers = '1234567890';

return R;
};
}
exports.randomString = randomString;
//# sourceMappingURL=helpers.js.map
import * as React from 'react';
import { InlineSVGError } from './helpers';
export interface IProps {
baseURL?: string;
cacheRequests?: boolean;
children?: React.ReactNode;
description?: string;
loader?: React.ReactNode;
innerRef?: React.Ref<HTMLElement>;
onError?: (error: InlineSVGError | IFetchError) => void;
onLoad?: (src: string, isCached: boolean) => void;
preProcessor?: (code: string) => string;
src: string;
title?: string;
uniqueHash?: string;
uniquifyIDs?: boolean;
[key: string]: any;
}
export interface IState {
content: string;
element: React.ReactNode;
hasCache: boolean;
status: string;
}
export interface IFetchError extends Error {
code: string;
errno: string;
message: string;
type: string;
}
export interface IStorageItem {
content: string;
queue: any[];
status: string;
}
export declare const STATUS: {
FAILED: string;
LOADED: string;
LOADING: string;
PENDING: string;
READY: string;
UNSUPPORTED: string;
};
export default class InlineSVG extends React.PureComponent<IProps, IState> {
import { Props, State } from './types';
export default class InlineSVG extends React.PureComponent<Props, State> {
constructor(props: Props);
private isActive;
private readonly hash;
static defaultProps: {

@@ -49,7 +11,4 @@ cacheRequests: boolean;

};
private _isMounted;
private readonly hash;
constructor(props: IProps);
componentDidMount(): void;
componentDidUpdate(prevProps: IProps, prevState: IState): void;
componentDidUpdate(prevProps: Props, prevState: State): void;
componentWillUnmount(): void;

@@ -64,3 +23,3 @@ private processSVG;

private request;
render(): {} | null;
render(): React.ReactNode;
}

@@ -61,10 +61,2 @@ "use strict";

var helpers_1 = require("./helpers");
exports.STATUS = {
FAILED: 'failed',
LOADED: 'loaded',
LOADING: 'loading',
PENDING: 'pending',
READY: 'ready',
UNSUPPORTED: 'unsupported',
};
var cacheStore = Object.create(null);

@@ -75,10 +67,9 @@ var InlineSVG = /** @class */ (function (_super) {

var _this = _super.call(this, props) || this;
// tslint:disable-next-line:variable-name
_this._isMounted = false;
_this.isActive = false;
_this.handleLoad = function (content) {
/* istanbul ignore else */
if (_this._isMounted) {
if (_this.isActive) {
_this.setState({
content: content,
status: exports.STATUS.LOADED,
status: helpers_1.STATUS.LOADED,
}, _this.getElement);

@@ -89,10 +80,10 @@ }

var onError = _this.props.onError;
var status = error.message === 'Browser does not support SVG' ? exports.STATUS.UNSUPPORTED : exports.STATUS.FAILED;
var status = error.message === 'Browser does not support SVG' ? helpers_1.STATUS.UNSUPPORTED : helpers_1.STATUS.FAILED;
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
// tslint:disable-next-line:no-console
// eslint-disable-next-line no-console
console.error(error);
}
/* istanbul ignore else */
if (_this._isMounted) {
if (_this.isActive) {
_this.setState({ status: status }, function () {

@@ -110,3 +101,3 @@ /* istanbul ignore else */

if (cacheRequests) {
cacheStore[src] = { content: '', status: exports.STATUS.LOADING, queue: [] };
cacheStore[src] = { content: '', status: helpers_1.STATUS.LOADING, queue: [] };
}

@@ -118,6 +109,6 @@ return fetch(src)

if (response.status > 299) {
throw new helpers_1.InlineSVGError('Not Found');
throw new Error('Not found');
}
if (!['image/svg+xml', 'text/plain'].some(function (d) { return fileType.indexOf(d) >= 0; })) {
throw new helpers_1.InlineSVGError("Content type isn't valid: " + fileType);
throw new Error("Content type isn't valid: " + fileType);
}

@@ -134,3 +125,3 @@ return response.text();

cache.content = content;
cache.status = exports.STATUS.LOADED;
cache.status = helpers_1.STATUS.LOADED;
cache.queue = cache.queue.filter(function (cb) {

@@ -152,3 +143,3 @@ cb(content);

catch (error) {
_this.handleError(new helpers_1.InlineSVGError(error.message));
return _this.handleError(new Error(error.message));
}

@@ -160,3 +151,3 @@ };

hasCache: !!props.cacheRequests && !!cacheStore[props.src],
status: exports.STATUS.PENDING,
status: helpers_1.STATUS.PENDING,
};

@@ -167,5 +158,4 @@ _this.hash = props.uniqueHash || helpers_1.randomString(8);

InlineSVG.prototype.componentDidMount = function () {
this._isMounted = true;
this.isActive = true;
if (!helpers_1.canUseDOM()) {
this.handleError(new helpers_1.InlineSVGError('No DOM'));
return;

@@ -177,10 +167,10 @@ }

/* istanbul ignore else */
if (status === exports.STATUS.PENDING) {
if (status === helpers_1.STATUS.PENDING) {
/* istanbul ignore else */
if (!helpers_1.isSupportedEnvironment()) {
throw new helpers_1.InlineSVGError('Browser does not support SVG');
throw new Error('Browser does not support SVG');
}
/* istanbul ignore else */
if (!src) {
throw new helpers_1.InlineSVGError('Missing src');
throw new Error('Missing src');
}

@@ -200,3 +190,3 @@ this.load();

var _b = this.props, onLoad = _b.onLoad, src = _b.src;
if (prevState.status !== exports.STATUS.READY && status === exports.STATUS.READY) {
if (prevState.status !== helpers_1.STATUS.READY && status === helpers_1.STATUS.READY) {
/* istanbul ignore else */

@@ -209,3 +199,3 @@ if (onLoad) {

if (!src) {
this.handleError(new helpers_1.InlineSVGError('Missing src'));
this.handleError(new Error('Missing src'));
return;

@@ -217,3 +207,3 @@ }

InlineSVG.prototype.componentWillUnmount = function () {
this._isMounted = false;
this.isActive = false;
};

@@ -241,8 +231,9 @@ InlineSVG.prototype.processSVG = function () {

if (d.attributes && d.attributes.length) {
var attributes_1 = Object.values(d.attributes);
attributes_1.forEach(function (a) {
var attributes_1 = Object.values(d.attributes).map(function (a) {
var attr = a;
var match = a.value.match(/url\((.*?)\)/);
if (match && match[1]) {
a.value = a.value.replace(match[0], "url(" + baseURL + match[1] + "__" + _this.hash + ")");
attr.value = a.value.replace(match[0], "url(" + baseURL + match[1] + "__" + _this.hash + ")");
}
return attr;
});

@@ -257,3 +248,3 @@ replaceableAttributes.forEach(function (r) {

if (d.children.length) {
d = _this.updateSVGAttributes(d);
return _this.updateSVGAttributes(d);
}

@@ -270,3 +261,3 @@ return d;

if (!node || !(node instanceof SVGSVGElement)) {
throw new helpers_1.InlineSVGError('Could not convert the src to a DOM Node');
throw new Error('Could not convert the src to a DOM Node');
}

@@ -295,3 +286,3 @@ var svg = this.updateSVGAttributes(node);

catch (error) {
this.handleError(error);
return this.handleError(error);
}

@@ -304,11 +295,11 @@ };

if (!element || !React.isValidElement(element)) {
throw new helpers_1.InlineSVGError('Could not convert the src to a React element');
throw new Error('Could not convert the src to a React element');
}
this.setState({
element: element,
status: exports.STATUS.READY,
status: helpers_1.STATUS.READY,
});
}
catch (error) {
this.handleError(new helpers_1.InlineSVGError(error.message));
this.handleError(new Error(error.message));
}

@@ -319,7 +310,7 @@ };

/* istanbul ignore else */
if (this._isMounted) {
if (this.isActive) {
this.setState({
content: '',
element: null,
status: exports.STATUS.LOADING,
status: helpers_1.STATUS.LOADING,
}, function () {

@@ -330,6 +321,6 @@ var _a = _this.props, cacheRequests = _a.cacheRequests, src = _a.src;

/* istanbul ignore else */
if (cache.status === exports.STATUS.LOADING) {
if (cache.status === helpers_1.STATUS.LOADING) {
cache.queue.push(_this.handleLoad);
}
else if (cache.status === exports.STATUS.LOADED) {
else if (cache.status === helpers_1.STATUS.LOADED) {
_this.handleLoad(cache.content);

@@ -356,11 +347,11 @@ }

InlineSVG.prototype.render = function () {
var _a = this.state, element = _a.element, status = _a.status;
var _b = this.props, baseURL = _b.baseURL, cacheRequests = _b.cacheRequests, _c = _b.children, children = _c === void 0 ? null : _c, description = _b.description, innerRef = _b.innerRef, _d = _b.loader, loader = _d === void 0 ? null : _d, onError = _b.onError, onLoad = _b.onLoad, preProcessor = _b.preProcessor, src = _b.src, title = _b.title, uniqueHash = _b.uniqueHash, uniquifyIDs = _b.uniquifyIDs, rest = __rest(_b, ["baseURL", "cacheRequests", "children", "description", "innerRef", "loader", "onError", "onLoad", "preProcessor", "src", "title", "uniqueHash", "uniquifyIDs"]);
if (!helpers_1.canUseDOM()) {
return null;
return loader;
}
var _a = this.state, element = _a.element, status = _a.status;
var _b = this.props, baseURL = _b.baseURL, cacheRequests = _b.cacheRequests, _c = _b.children, children = _c === void 0 ? null : _c, description = _b.description, innerRef = _b.innerRef, _d = _b.loader, loader = _d === void 0 ? null : _d, onError = _b.onError, onLoad = _b.onLoad, preProcessor = _b.preProcessor, src = _b.src, title = _b.title, uniqueHash = _b.uniqueHash, uniquifyIDs = _b.uniquifyIDs, rest = __rest(_b, ["baseURL", "cacheRequests", "children", "description", "innerRef", "loader", "onError", "onLoad", "preProcessor", "src", "title", "uniqueHash", "uniquifyIDs"]);
if (element) {
return React.cloneElement(element, __assign({ ref: innerRef }, rest));
}
if ([exports.STATUS.UNSUPPORTED, exports.STATUS.FAILED].indexOf(status) > -1) {
if ([helpers_1.STATUS.UNSUPPORTED, helpers_1.STATUS.FAILED].indexOf(status) > -1) {
return children;

@@ -367,0 +358,0 @@ }

{
"name": "react-inlinesvg",
"version": "1.2.0",
"version": "2.0.0",
"description": "An SVG loader for React",

@@ -21,7 +21,10 @@ "author": "Gil Barbara <gilbarbara@gmail.com>",

"main": "lib/index.js",
"module": "esm/index.js",
"files": [
"esm",
"lib",
"src"
],
"types": "lib/index.d.ts",
"types": "lib",
"sideEffects": true,
"license": "MIT",

@@ -33,64 +36,67 @@ "keywords": [

"peerDependencies": {
"react": "^16.3.0"
"react": "^16.8.0"
},
"dependencies": {
"exenv": "^1.2.2",
"react-from-dom": "^0.3.0"
"react-from-dom": "^0.4.2"
},
"devDependencies": {
"@gilbarbara/tsconfig": "^0.1.0",
"@size-limit/preset-small-lib": "^2.2.1",
"@types/enzyme": "^3.10.3",
"@types/enzyme-adapter-react-16": "^1.0.5",
"@size-limit/preset-small-lib": "^4.5.1",
"@types/enzyme": "^3.10.5",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@types/exenv": "^1.2.0",
"@types/fetch-mock": "^7.3.2",
"@types/jest": "^24.0.23",
"@types/node": "^12.12.9",
"@types/node-fetch": "^2.5.3",
"@types/react": "^16.9.11",
"@types/react-dom": "^16.9.4",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"fetch-mock": "^8.0.0",
"http-server": "^0.11.1",
"husky": "^3.1.0",
"jest": "^24.9.0",
"jest-chain": "^1.1.2",
"@types/jest": "^26.0.0",
"@types/node": "^14.0.13",
"@types/node-fetch": "^2.5.7",
"@types/react": "^16.9.38",
"@types/react-dom": "^16.9.8",
"@typescript-eslint/eslint-plugin": "^3.3.0",
"@typescript-eslint/parser": "^3.3.0",
"del-cli": "^3.0.1",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.21.2",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.0",
"http-server": "^0.12.3",
"husky": "^4.2.5",
"jest": "^26.0.1",
"jest-chain": "^1.1.5",
"jest-enzyme": "^7.1.2",
"jest-extended": "^0.11.2",
"jest-watch-typeahead": "^0.4.2",
"jest-extended": "^0.11.5",
"jest-fetch-mock": "^3.0.3",
"jest-watch-typeahead": "^0.6.0",
"node-fetch": "^2.6.0",
"prettier": "^1.19.1",
"prettier": "^2.0.5",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-dom": "^16.13.1",
"repo-tools": "^0.2.0",
"rimraf": "^3.0.0",
"size-limit": "^2.2.1",
"start-server-and-test": "^1.10.6",
"ts-jest": "^24.1.0",
"tslint": "^5.20.1",
"tslint-config-prettier": "^1.18.0",
"tslint-react": "^4.1.0",
"typescript": "^3.7.2"
"size-limit": "^4.5.1",
"start-server-and-test": "^1.11.0",
"ts-jest": "^26.1.0",
"typescript": "^3.9.5"
},
"scripts": {
"build": "npm run clean && npm run build:ts",
"build:ts": "tsc",
"watch": "npm run build:ts -- -w",
"clean": "rimraf lib",
"start": "http-server -p 1337 --cors test/__fixtures__",
"build": "npm run clean && npm run build:cjs && npm run build:esm",
"build:cjs": "tsc",
"build:esm": "tsc -m es6 --outDir esm",
"clean": "del lib/* && del esm/*",
"watch:cjs": "npm run build:cjs -- -w",
"watch:esm": "npm run build:esm -- -w",
"start": "http-server test/__fixtures__ -p 1337 --cors",
"test": "start-server-and-test start http://localhost:1337 test:coverage",
"test:coverage": "jest --coverage --bail",
"test:watch": "jest --watch --verbose",
"lint": "tslint 'src/**/*.ts?(x)' 'test/**/*.ts?(x)' 'tools/**/*.ts?(x)'",
"lint": "eslint --ext .ts,.tsx src test",
"format": "prettier \"**/*.{js,jsx,json,yml,yaml,css,less,scss,ts,tsx,md,graphql,mdx}\" --write",
"validate": "npm run lint && npm run test && npm run size",
"size": "npm run build && size-limit",
"validate": "npm run lint && npm run test && npm run build && npm run size",
"size": "size-limit",
"prepublishOnly": "npm run validate"
},
"browserslist": [
"> 0.2%",
"safari >= 9",
"ios >= 9"
],
"prettier": {

@@ -105,3 +111,7 @@ "jsxBracketSameLine": false,

"path": "./lib/index.js",
"limit": "8 KB"
"limit": "8 kB"
},
{
"path": "./esm/index.js",
"limit": "8 kB"
}

@@ -111,3 +121,3 @@ ],

"hooks": {
"post-merge": "repo-tools istall-packages",
"post-merge": "repo-tools install-packages",
"pre-commit": "repo-tools check-remote && npm run validate"

@@ -114,0 +124,0 @@ }

@@ -5,5 +5,12 @@ # react-inlinesvg

Load inline, local or remote SVGs in your React components.
Async requests will be cached.
Load inline, local or remote SVGs in your React components.
## Highlights
- 🏖 **Easy to use:** Just set the `src`
- 🛠 **Flexible:** Personalize the options to fit your needs
- ⚡️ **Smart:** Async requests will be cached.
- 🚀 **SSR:** Render a loader until the DOM is available
- 🟦 **Typescript:** Nicely typed
## Usage

@@ -21,3 +28,3 @@

const Icon = () => <SVG src="/path/to/myfile.svg" />;
const Icon = () => <SVG src={require('/path/to/myfile.svg')} />;
```

@@ -28,3 +35,4 @@

**src** {string} - **required**.
The SVG file you want to load. It can be an `url` or a string (base64 or encoded).
The SVG file you want to load. It can be a require, URL or a string (base64 or url encoded).
*If you are using create-react-app and your file resides in the `public` directory you can use the path directly without require.*

@@ -44,3 +52,4 @@ **baseURL** {string}

**loader** {node}
A component to be shown while the SVG is loading.
A component to be shown while the SVG is loading.
If you set

@@ -97,3 +106,3 @@ **onError** {function}

description="The React logo"
loader={() => <span>Loading...</span>}
loader={<span>Loading...</span>}
onError={error => console.log(error.message)}

@@ -112,5 +121,5 @@ onLoad={(src, hasCache) => console.log(src, hasCache)}

Any browsers that support inlining [SVGs](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) and [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) will work.
If you need to support legacy browsers you'll need to include a polyfiil in your app.
Take a look at [react-app-polyfill](https://www.npmjs.com/package/react-app-polyfill).
If you need to support legacy browsers you'll need to include a polyfiil for `fetch` and `Number.isNaN` in your app. Take a look at [react-app-polyfill](https://www.npmjs.com/package/react-app-polyfill) or [polyfill.io](https://polyfill.io/v3/).
## CORS

@@ -117,0 +126,0 @@

import { canUseDOM as canUseDOMFlag } from 'exenv';
export const canUseDOM = () => canUseDOMFlag;
export const STATUS = {
FAILED: 'failed',
LOADED: 'loaded',
LOADING: 'loading',
PENDING: 'pending',
READY: 'ready',
UNSUPPORTED: 'unsupported',
};
export const supportsInlineSVG = () => {
export function canUseDOM(): boolean {
return canUseDOMFlag;
}
export function supportsInlineSVG(): boolean {
/* istanbul ignore next */

@@ -13,26 +24,10 @@ if (!document) {

div.innerHTML = '<svg />';
return div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg';
};
return !!div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg';
}
// tslint:disable-next-line:no-shadowed-variable
export class InlineSVGError extends Error {
public name: string;
public message: string;
public data?: object;
constructor(message: string, data?: object) {
super();
this.name = 'InlineSVGError';
this.message = message;
this.data = data;
return this;
}
export function isSupportedEnvironment(): boolean {
return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;
}
export const isSupportedEnvironment = () =>
supportsInlineSVG() && typeof window !== 'undefined' && window !== null;
export const randomString = (length: number) => {
export function randomString(length: number): string {
const letters = 'abcdefghijklmnopqrstuvwxyz';

@@ -49,3 +44,4 @@ const numbers = '1234567890';

}
return R;
};
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc