Skip to content

Commit

Permalink
feat(create): create any svg element via markup
Browse files Browse the repository at this point in the history
Allow non <SVG> elements to be created from markup:

```javascript
var g = create('<g id="G" />');
```
  • Loading branch information
nikku committed Oct 4, 2018
1 parent ddeaba9 commit 7821463
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 4 deletions.
19 changes: 18 additions & 1 deletion lib/util/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ var SVG_START = '<svg xmlns="' + ns.svg + '"';

export default function parse(svg) {

var unwrap = false;

// ensure we import a valid svg document
if (svg.substring(0, 4) === '<svg') {
if (svg.indexOf(ns.svg) === -1) {
Expand All @@ -16,9 +18,24 @@ export default function parse(svg) {
} else {
// namespace svg
svg = SVG_START + '>' + svg + '</svg>';
unwrap = true;
}

var parsed = parseDocument(svg);

if (!unwrap) {
return parsed;
}

var fragment = document.createDocumentFragment();

var parent = parsed.firstChild;

while (parent.firstChild) {
fragment.appendChild(parent.firstChild);
}

return parseDocument(svg);
return fragment;
}

function parseDocument(svg) {
Expand Down
20 changes: 19 additions & 1 deletion test/spec/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('create', function() {
});


it('should create element from SVG markup', function() {
it('should create <svg> from markup', function() {

// given
var container = createContainer();
Expand All @@ -50,4 +50,22 @@ describe('create', function() {
expect(svg.childNodes[0].nodeName).to.eql('g');
});


it('should create <g> from markup', function() {

// given
var container = createContainer();

// when
var g = create('<g id="G"><circle cx="10" cy="10" r="2"></circle></g>');

append(container, g);

// then
expect(g.nodeName).to.eql('g');
expect(g.id).to.eql('G');
expect(g.childNodes.length).to.eql(1);
expect(g.childNodes[0].nodeName).to.eql('circle');
});

});
18 changes: 16 additions & 2 deletions test/spec/util/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {

import parse from '../../../lib/util/parse';


describe('parse', function() {

it('should parse <defs> / CDATA', function() {
Expand All @@ -16,13 +17,26 @@ describe('parse', function() {
']]></style>' +
'</defs>';

// when
var fragment = parse(text);
var svg = innerSVG(fragment);

// then
expect(svg).to.eql(text);
});


it('should parse <svg>', function() {

// given
var text = '<svg><g id="1"/><circle/></svg>';

// when
var doc = parse(text);
var svg = innerSVG(doc.documentElement);
var svg = innerSVG(doc);

// then
expect(svg).to.eql(text);
expect(svg).to.eql('<svg xmlns="http://www.w3.org/2000/svg"><g id="1"/><circle/></svg>');
});

});

0 comments on commit 7821463

Please sign in to comment.