1 | 'use strict'
|
2 |
|
3 |
|
4 | const sanitizeIcon = icon =>
|
5 | icon
|
6 | .replace(/class="(.*?)"/, '')
|
7 | .replace(/fill="(.*?)"/g, '')
|
8 |
|
9 | class Icon {
|
10 | constructor (name, content) {
|
11 | this.name = name
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const template = document.createElement('template')
|
17 | template.innerHTML = content
|
18 | this.svgTemplateNode = document.adoptNode(template.content)
|
19 | .querySelector('svg')
|
20 |
|
21 |
|
22 | this.svgTemplateContent = document.createDocumentFragment()
|
23 | for (const child of this.svgTemplateNode.childNodes) {
|
24 |
|
25 | if (child.nodeType === Node.TEXT_NODE) continue
|
26 | this.svgTemplateContent.appendChild(child)
|
27 | }
|
28 | }
|
29 |
|
30 | insert (svgNode) {
|
31 |
|
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 |
|
41 | class 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 |
|
65 | selection.nodes().forEach(node => icon.insert(node))
|
66 | }
|
67 | }
|
68 | }
|
69 |
|
70 | module.exports = new Icons()
|