UNPKG

3.39 kBJavaScriptView Raw
1'use strict';
2
3exports.type = 'perItemReverse';
4
5exports.active = true;
6
7exports.description = 'moves elements attributes to the existing group wrapper';
8
9var inheritableAttrs = require('./_collections').inheritableAttrs,
10 pathElems = require('./_collections.js').pathElems;
11
12/**
13 * Collapse content's intersected and inheritable
14 * attributes to the existing group wrapper.
15 *
16 * @example
17 * <g attr1="val1">
18 * <g attr2="val2">
19 * text
20 * </g>
21 * <circle attr2="val2" attr3="val3"/>
22 * </g>
23 * ⬇
24 * <g attr1="val1" attr2="val2">
25 * <g>
26 * text
27 * </g>
28 * <circle attr3="val3"/>
29 * </g>
30 *
31 * @param {Object} item current iteration item
32 * @return {Boolean} if false, item will be filtered out
33 *
34 * @author Kir Belevich
35 */
36exports.fn = function(item) {
37
38 if (item.isElem('g') && !item.isEmpty() && item.content.length > 1) {
39
40 var intersection = {},
41 hasTransform = false,
42 hasClip = item.hasAttr('clip-path') || item.hasAttr('mask'),
43 intersected = item.content.every(function(inner) {
44 if (inner.isElem() && inner.hasAttr()) {
45 // don't mess with possible styles (hack until CSS parsing is implemented)
46 if (inner.hasAttr('class')) return false;
47 if (!Object.keys(intersection).length) {
48 intersection = inner.attrs;
49 } else {
50 intersection = intersectInheritableAttrs(intersection, inner.attrs);
51
52 if (!intersection) return false;
53 }
54
55 return true;
56 }
57 }),
58 allPath = item.content.every(function(inner) {
59 return inner.isElem(pathElems);
60 });
61
62 if (intersected) {
63
64 item.content.forEach(function(g) {
65
66 for (var name in intersection) {
67
68 if (!allPath && !hasClip || name !== 'transform') {
69
70 g.removeAttr(name);
71
72 if (name === 'transform') {
73 if (!hasTransform) {
74 if (item.hasAttr('transform')) {
75 item.attr('transform').value += ' ' + intersection[name].value;
76 } else {
77 item.addAttr(intersection[name]);
78 }
79
80 hasTransform = true;
81 }
82 } else {
83 item.addAttr(intersection[name]);
84 }
85
86 }
87 }
88
89 });
90
91 }
92
93 }
94
95};
96
97/**
98 * Intersect inheritable attributes.
99 *
100 * @param {Object} a first attrs object
101 * @param {Object} b second attrs object
102 *
103 * @return {Object} intersected attrs object
104 */
105function intersectInheritableAttrs(a, b) {
106
107 var c = {};
108
109 for (var n in a) {
110 if (
111 b.hasOwnProperty(n) &&
112 inheritableAttrs.indexOf(n) > -1 &&
113 a[n].name === b[n].name &&
114 a[n].value === b[n].value &&
115 a[n].prefix === b[n].prefix &&
116 a[n].local === b[n].local
117 ) {
118 c[n] = a[n];
119 }
120 }
121
122 if (!Object.keys(c).length) return false;
123
124 return c;
125
126}