tanem / svg-injector Goto Github PK
View Code? Open in Web Editor NEW:syringe: Fast, caching, dynamic inline SVG DOM injection library.
Home Page: https://npm.im/@tanem/svg-injector
License: MIT License
:syringe: Fast, caching, dynamic inline SVG DOM injection library.
Home Page: https://npm.im/@tanem/svg-injector
License: MIT License
In some of the exported SVGs, inside defs I have something like:
<defs>
<path id="a" d="...." />
</defs>
Which is then used inside <g>
, as:
<g>
<mask id="b" fill="#fff">
<use xlink:href="#a" />
</mask>
<use fill="#000" xlink:href="#a"/>
<g mask="url(#b)">
<path fill="#FFF" d="...."/>
</g>
</g>
When having many elements like these, the svg graphics get mixed up. This example also has the problem of defining the id of the mask outside <defs>
, and using reference it by id... should I raise a separate issue for that?
Hello, we use react-svg and have trouble with clip-paths not being applied correctly, turns out clip-path ids get randomized, but same ids are not updated in clip-path style attribute
svg-injector/src/inject-element.ts
Lines 155 to 186 in b7200f5
Thanks in advance!
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@tanem/svg-injector/-/svg-injector-8.0.61.tgz
npm ERR! 404
npm ERR! 404 '@tanem/[email protected]' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-08-06T08_58_33_447Z-debug.log
When injecting, the resulting SVG has class
attribute as class="[object Set]"
. This can be seen on Basic Usage example on Chrome 71.0.3578.98 64-bit on macOS Mojave v10.14.12.
Screenshot for reference:
It seems after some frustrating time that the plugin doesn't correctly handle SVGs that are hosted on and CDN like Cloudfront. Might this issue be related?
To me it seems such a big issue that I'm starting to doubt myself if I just am missing something obvious.
Hi there,
I'm using this library through react-svg in a server-less PWA I maintain. As a PWA, it caches the assets, so it can work offline. But some data-related assets are not downloaded until requested by the user. Sometimes, the user may forget to disable phone's airplane mode before using the app. Note: In this app, the SVG related component can be seen by adding a Map Widget.
I am developing an error boundary which allows re-rendering the errorish component once the source of the error have been fixed (for example, disabling phone's airplane mode). In this case, I expect the ReactSVG component to retry the download. Instead of that, it reuses a cached errorish version of the fetched data. Note: Using DevTools Network, I am able to mock an initial error from server by blocking the SVG URL, and then "un-block" the net request for the SVG to retry the component render.
As a workaround, I create a global object where I store successful downloads by src
(set on afterInjection
) and set react.svg
's useRequestCache
(same as this package's cacheRequests
) to false until a successful download is detected.
I think it would be much better to don't cache errorish responses (unless -maybe- otherwise stated).
Note: I open the issue directly here, as I think the fix would be desired here, too, and the author is the same for both projects.
Sorry to be the one that brings up IE support, but I've tracked down react-svg
not working to here :(
https://github.com/tanem/svg-injector/blob/master/src/inject-element.ts#L85 uses Array.from
which isn't in IE11 yet. I've got core-js in my webpack build but I'm using babel-preset-env with useBuiltins
set to usage
, but because your code comes from an npm module, webpack never checks it so I don't get the polyfill for Array.from
.
Anything you can do to fix, or shall I just force the Array.from
polyfill from core-js into my build?
Hello,
Is it possible to use the library to deal with SVG sprites?
<svg
fill="#f00"
...
>
<use xlink:href="/sprite.svg#specific-icon"></use>
</svg>
Example: https://codepen.io/supersimplenet/pen/zYvbPyN
Thank you
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates are awaiting their schedule. Click on a checkbox to get an update now.
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
@typescript-eslint/eslint-plugin
, @typescript-eslint/parser
)These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@babel/core
, @babel/plugin-transform-runtime
, @babel/preset-env
, @babel/preset-typescript
, @babel/runtime
)chai
, @types/chai
).github/workflows/ci.yml
styfle/cancel-workflow-action 0.12.1
actions/checkout v4
actions/checkout v4
actions/setup-node v4
codecov/codecov-action v3
examples/api-usage/package.json
parcel 2.10.0
examples/basic-usage/package.json
parcel 2.10.0
examples/mootools/package.json
parcel 2.10.0
examples/umd-dev/package.json
examples/umd-prod/package.json
package.json
@babel/runtime ^7.23.2
content-type ^1.0.5
tslib ^2.6.2
@babel/core 7.23.2
@babel/plugin-transform-runtime 7.23.2
@babel/preset-env 7.23.2
@babel/preset-typescript 7.23.2
@rollup/plugin-babel 6.0.4
@rollup/plugin-commonjs 25.0.7
@rollup/plugin-node-resolve 15.2.3
@rollup/plugin-replace 5.0.5
@rollup/plugin-terser 0.4.4
@types/chai 4.3.8
@types/content-type 1.1.8
@types/karma 6.3.8
@types/karma-chai 0.1.6
@types/mocha 9.1.1
@types/sinon 9.0.11
@types/ua-parser-js 0.7.39
@types/webpack-env 1.18.4
@typescript-eslint/eslint-plugin 7.6.0
@typescript-eslint/parser 7.6.0
babel-loader 9.1.3
babel-plugin-istanbul 6.1.1
chai 4.3.10
eslint 8.57.0
eslint-config-prettier 9.1.0
karma 6.4.3
karma-browserstack-launcher 1.6.0
karma-chai 0.1.0
karma-chrome-launcher 3.2.0
karma-coverage-istanbul-reporter 3.0.3
karma-mocha 2.0.1
karma-sourcemap-loader 0.4.0
karma-spec-reporter 0.0.36
karma-webpack 5.0.1
mocha 9.2.2
npm-run-all 4.1.5
null-loader 4.0.1
prettier 3.0.3
query-string 7.1.3
rollup 4.13.1
rollup-plugin-filesize 10.0.0
shx 0.3.4
sinon 9.2.4
tanem-scripts 7.0.26
typescript 5.4.4
ua-parser-js 1.0.37
webpack 5.91.0
.nvmrc
I'm using react-svg and the beforeInjection callback doesn't let me access the style property on the svg. It's because the type is Element.
const beforeInject = (svg: Element) => {
svg.style.backgroundImage = `url(${texture.url})` // TS2339: Property 'style' does not exist on type 'Element'.
svg.style.width = `${size.width}px`,
svg.style.clipPath = `url(#${id})`
}
It's not really a problem as this works
const beforeInject = (s: Element) => {
const svg = s as HTMLElement
svg.style.backgroundImage = `url(${texture.url})`
svg.style.width = `${size.width}px`,
svg.style.clipPath = `url(#${id})`
}
but I was wondering if it's intended or a mistake?
Hello tanem,
We are using image calls to have an image and I am using (load)="SVGInjector()". Although we are setting the token for the call in cookies and in the request header it should pass the token but it seems like it's not. Do you have a solution for it? (we tried by putting httpRequest.withCredentials = true; in file https://github.com/tanem/svg-injector/blob/master/src/make-ajax-request.ts) and it works so do we have another version where we can have something like this?
Sorry my code is behind a firewall so it is not available to run an example. I have a page where I use the same svg source in multiple places but sometimes the svg fails to be injected. Instead I get the following div.
<div data-src="Pub/Web/Icon/arrowDropDown.svg" src(unknown)></div>
If I perform an action to cause the svg container to render again the svg will show. I am running on a web server not locally. Any advice is appreciated.
I have build an Icon component that allows me to pass a fill color as props to an svg. It works if the fill color remains static, but I would like to have the colors update if new fill props are passed. In the code bellow, I am re-injecting the svg with the new color props in componentDidUpdate
but the svg keeps the old colors in the browser. Could this be caused by cacheing? If so, how to I get around this?
import React, { PureComponent, createRef } from 'react';
import PropTypes from 'prop-types';
import SVGInjector from '@tanem/svg-injector';
class Icon extends PureComponent {
static propTypes = {
/**
* Name of the SVG icon
*/
name: PropTypes.string.isRequired,
/**
* Optional fill color - default is black
* If an array is passed the colors will be mapped over the <path> tags within the SVG
*/
fill: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
/**
* Optional CSS class
*/
className: PropTypes.string,
/**
* Optional style object
*/
style: PropTypes.shape({}),
};
static defaultProps = {
fill: '#000',
className: '',
style: {},
};
constructor(props) {
super(props);
this.svgRef = createRef();
this.createSvgOptions = this.createSvgOptions.bind(this);
}
componentDidMount() {
SVGInjector(this.svgRef.current, this.createSvgOptions());
}
componentDidUpdate(prevProps) {
if (prevProps.fill !== this.props.fill) {
SVGInjector(this.svgRef.current, this.createSvgOptions());
}
}
createSvgOptions() {
const { fill } = this.props;
return {
each(err, svg) {
if (err) {
throw err;
}
const paths = Array.from(svg.getElementsByTagName('path'));
if (typeof fill === 'string') {
paths.forEach(path => path.setAttribute('fill', fill));
} else if (Array.isArray(fill)) {
paths.forEach((path, i) => {
const color = fill[i] ? fill[i] : fill[0]; // if less colors than paths, use first color
path.setAttribute('fill', color);
});
}
},
}
}
render() {
const { className, style, name } = this.props;
return (
<span
ref={this.svgRef}
className={className}
style={style}
data-src={`https://my-cdn.com/icons/${name}.svg`}
/>
);
}
}
export default Icon;
For ESM module, you currently have this:
import SVGInjector from './svg-injector';
export default SVGInjector;
While this can be resolved to /svg-injector.js
, when using as ES6 module, the browser can't resolve and won't import the library.
Please consider adding .js
to all your imports, either manually or through babel.
Hello tahem!
We've run into one very nasty conflict on several client sites where we use the SVG Injector.
They use a very very ancient library called "mootools" with this interesting method that overriding window.Document (such a shame). https://mootools.net/core/docs/1.6.0/Element/Element#Window:document-id
As a consequence, the instanceof Document
check fails. (load-svg-cached.ts and load-svg-uncached.ts)
From the user-land side, we cannot influence this in any way and are thinking about a stub.
Could you add some fallback if this check fails on your end?
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.
Can i get original element before transformation in beforeEach?
I need to apply some attributes as original img tag has.
Thanks in advance!
For example, width
, height
, alt
, title
, etc...
This is probably opinionated. For me, if I use the SVG in <img>
, and I set width
and height
, I would think that the injected SVG should keep the same dimension. Otherwise, when using in IE10-, if the SVG itself does not have width
and height
, IE will display it using the default dimension.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.