UNPKG

2.71 kBJavaScriptView Raw
1'use strict'
2/* global Node */
3
4const sanitizeIcon = icon =>
5 icon
6 .replace(/class="(.*?)"/, '')
7 .replace(/fill="(.*?)"/g, '')
8
9class Icon {
10 constructor (name, content) {
11 this.name = name
12
13 // parse content though a documentFragment. Note that documentFragments
14 // themself doesn't support innerHTML, so use a template element and
15 // access its content property, which is a documentFragment itself.
16 const template = document.createElement('template')
17 template.innerHTML = content
18 this.svgTemplateNode = document.adoptNode(template.content)
19 .querySelector('svg')
20
21 // Extract svg content into a template for easier insertion
22 this.svgTemplateContent = document.createDocumentFragment()
23 for (const child of this.svgTemplateNode.childNodes) {
24 // svg can not have root text nodes, so skip these.
25 if (child.nodeType === Node.TEXT_NODE) continue
26 this.svgTemplateContent.appendChild(child)
27 }
28 }
29
30 insert (svgNode) {
31 // DOM node attributes list is not iterable in MS Edge, but can be turned into an array
32 const attributes = this.svgTemplateNode.attributes
33 const iterableAttributes = typeof attributes[Symbol.iterator] === 'function' ? attributes : Array.from(attributes)
34 for (const attr of iterableAttributes) {
35 svgNode.setAttribute(attr.name, attr.value)
36 }
37 svgNode.appendChild(this.svgTemplateContent.cloneNode(true))
38 }
39}
40
41class Icons {
42 constructor () {
43 const icons = {
44 'arrow-down': sanitizeIcon(require('@nearform/clinic-common/icons/chevron-down')),
45 'arrow-up': sanitizeIcon(require('@nearform/clinic-common/icons/chevron-up')),
46 'arrow-right': sanitizeIcon(require('@nearform/clinic-common/icons/chevron-right')),
47 'arrow-left': sanitizeIcon(require('@nearform/clinic-common/icons/chevron-left')),
48 close: sanitizeIcon(require('@nearform/clinic-common/icons/close')),
49 'grid-1x4': sanitizeIcon(require('@nearform/clinic-common/icons/list-view')),
50 'grid-2x2': sanitizeIcon(require('@nearform/clinic-common/icons/grid-view')),
51 theme: sanitizeIcon(require('@nearform/clinic-common/icons/eye-show')),
52 warning: sanitizeIcon(require('@nearform/clinic-common/icons/warning-triangle'))
53 }
54
55 this._icons = new Map()
56 for (const [key, content] of Object.entries(icons)) {
57 this._icons.set(key, new Icon(key, content))
58 }
59 }
60
61 insertIcon (name) {
62 const icon = this._icons.get(name)
63 return function (selection) {
64 // d3's selection.nodes() is an array, but for ... of breaks MS Edge, can't see the array's [Symbol.iterator]
65 selection.nodes().forEach(node => icon.insert(node))
66 }
67 }
68}
69
70module.exports = new Icons()