UNPKG

simplesvg

Version:

A very simple svg wrapper, inspired by original vivagraph

121 lines (93 loc) 2.9 kB
module.exports = svg; svg.compile = require('./lib/compile'); var compileTemplate = svg.compileTemplate = require('./lib/compile_template'); var domEvents = require('add-event-listener'); var svgns = "http://www.w3.org/2000/svg"; var xlinkns = "http://www.w3.org/1999/xlink"; function svg(element, attrBag) { var svgElement = augment(element); if (attrBag === undefined) { return svgElement; } svgElement.attr(attrBag); return svgElement; } function augment(element) { var svgElement = element; if (typeof element === "string") { svgElement = window.document.createElementNS(svgns, element); } else if (element.simplesvg) { return element; } var compiledTemplate; svgElement.simplesvg = true; // this is not good, since we are monkey patching svg svgElement.attr = attr; svgElement.append = append; svgElement.link = link; svgElement.text = text; // add easy eventing svgElement.on = on; svgElement.off = off; // data binding: svgElement.dataSource = dataSource; return svgElement; function dataSource(model) { if (!compiledTemplate) compiledTemplate = compileTemplate(svgElement); compiledTemplate.link(model); return svgElement; } function on(name, cb, useCapture) { domEvents.addEventListener(svgElement, name, cb, useCapture); return svgElement; } function off(name, cb, useCapture) { domEvents.removeEventListener(svgElement, name, cb, useCapture); return svgElement; } function append(content) { var child = svg(content); svgElement.appendChild(child); return child; } function attr(name, value) { if (arguments.length === 2) { if (value !== null) { svgElement.setAttributeNS(null, name, value); } else { svgElement.removeAttributeNS(null, name); } return svgElement; } if (typeof name === 'string') { // someone wants to get value of an attribute: return svgElement.getAttributeNS(null, name); } if (typeof name !== 'object') throw new Error('attr() expects to have either string or object as first argument'); var attrBag = name; var attributes = Object.keys(attrBag); for (var i = 0; i < attributes.length; ++i) { var attributeName = attributes[i]; var value = attrBag[attributeName]; if (attributeName === 'link') { svgElement.link(value); } else { svgElement.attr(attributeName, value); } } return svgElement; } function link(target) { if (arguments.length) { svgElement.setAttributeNS(xlinkns, "xlink:href", target); return svgElement; } return svgElement.getAttributeNS(xlinkns, "xlink:href"); } function text(textContent) { if (textContent !== undefined) { svgElement.textContent = textContent; return svgElement; } return svgElement.textContent; } }