nav tabs on admin dashboard

This commit is contained in:
2019-03-07 00:20:34 -06:00
parent f73d6ae228
commit e4f473f376
11661 changed files with 216240 additions and 1544253 deletions

View File

@@ -1,6 +1,6 @@
'use strict';
// http://www.w3.org/TR/SVG/intro.html#Definitions
// http://www.w3.org/TR/SVG11/intro.html#Definitions
exports.elemsGroups = {
animation: ['animate', 'animateColor', 'animateMotion', 'animateTransform', 'set'],
descriptive: ['desc', 'metadata', 'title'],
@@ -17,7 +17,7 @@ exports.elemsGroups = {
exports.pathElems = ['path', 'glyph', 'missing-glyph'];
// http://www.w3.org/TR/SVG/intro.html#Definitions
// http://www.w3.org/TR/SVG11/intro.html#Definitions
exports.attrsGroups = {
animationAddition: ['additive', 'accumulate'],
animationAttributeTarget: ['attributeType', 'attributeName'],
@@ -30,7 +30,6 @@ exports.attrsGroups = {
presentation: [
'alignment-baseline',
'baseline-shift',
'buffered-rendering',
'clip',
'clip-path',
'clip-rule',
@@ -60,7 +59,6 @@ exports.attrsGroups = {
'glyph-orientation-horizontal',
'glyph-orientation-vertical',
'image-rendering',
'kerning',
'letter-spacing',
'lighting-color',
'marker-end',
@@ -69,10 +67,9 @@ exports.attrsGroups = {
'mask',
'opacity',
'overflow',
'paint-order',
'pointer-events',
'shape-rendering',
'solid-color',
'solid-opacity',
'stop-color',
'stop-opacity',
'stroke',
@@ -83,18 +80,14 @@ exports.attrsGroups = {
'stroke-miterlimit',
'stroke-opacity',
'stroke-width',
'paint-order',
'text-anchor',
'text-decoration',
'text-overflow',
'white-space',
'text-rendering',
'transform',
'unicode-bidi',
'vector-effect',
'viewport-fill',
'viewport-fill-opacity',
'visibility',
'white-space',
'word-spacing',
'writing-mode'
],
@@ -113,8 +106,6 @@ exports.attrsGroupsDefaults = {
'clip-rule': 'nonzero',
mask: 'none',
opacity: '1',
'solid-color': '#000',
'solid-opacity': '1',
'stop-color': '#000',
'stop-opacity': '1',
'fill-opacity': '1',
@@ -130,8 +121,6 @@ exports.attrsGroupsDefaults = {
'stroke-opacity': '1',
'paint-order': 'normal',
'vector-effect': 'none',
'viewport-fill': 'none',
'viewport-fill-opacity': '1',
display: 'inline',
visibility: 'visible',
'marker-start': 'none',
@@ -143,7 +132,6 @@ exports.attrsGroupsDefaults = {
'shape-rendering': 'auto',
'text-rendering': 'auto',
'image-rendering': 'auto',
'buffered-rendering': 'auto',
'font-style': 'normal',
'font-variant': 'normal',
'font-weight': 'normal',
@@ -168,7 +156,7 @@ exports.attrsGroupsDefaults = {
transferFunction: {slope: '1', intercept: '0', amplitude: '1', exponent: '1', offset: '0'}
};
// http://www.w3.org/TR/SVG/eltindex.html
// http://www.w3.org/TR/SVG11/eltindex.html
exports.elems = {
a: {
attrsGroups: [
@@ -788,6 +776,7 @@ exports.elems = {
'style',
'externalResourcesRequired',
'preserveAspectRatio',
'href',
'xlink:href'
],
defaults: {
@@ -1002,6 +991,7 @@ exports.elems = {
'filterRes',
'filterUnits',
'primitiveUnits',
'href',
'xlink:href'
],
defaults: {
@@ -1140,6 +1130,7 @@ exports.elems = {
'xlink'
],
attrs: [
'href',
'xlink:href'
],
content: [
@@ -1384,6 +1375,7 @@ exports.elems = {
'y',
'width',
'height',
'href',
'xlink:href'
],
defaults: {
@@ -1441,6 +1433,7 @@ exports.elems = {
'gradientUnits',
'gradientTransform',
'spreadMethod',
'href',
'xlink:href'
],
defaults: {
@@ -1620,6 +1613,7 @@ exports.elems = {
],
attrs: [
'externalResourcesRequired',
'href',
'xlink:href'
],
contentGroups: [
@@ -1666,6 +1660,7 @@ exports.elems = {
'patternUnits',
'patternContentUnits',
'patternTransform',
'href',
'xlink:href'
],
defaults: {
@@ -1762,6 +1757,7 @@ exports.elems = {
'gradientUnits',
'gradientTransform',
'spreadMethod',
'href',
'xlink:href'
],
defaults: {
@@ -1871,6 +1867,7 @@ exports.elems = {
attrs: [
'externalResourcesRequired',
'type',
'href',
'xlink:href'
]
},
@@ -2119,6 +2116,7 @@ exports.elems = {
'class',
'style',
'externalResourcesRequired',
'href',
'xlink:href',
'startOffset',
'method',
@@ -2164,6 +2162,7 @@ exports.elems = {
'class',
'style',
'externalResourcesRequired',
'href',
'xlink:href'
],
contentGroups: [
@@ -2224,6 +2223,7 @@ exports.elems = {
'y',
'width',
'height',
'href',
'xlink:href'
],
defaults: {
@@ -2279,10 +2279,18 @@ exports.editorNamespaces = [
'http://ns.adobe.com/Flows/1.0/',
'http://ns.adobe.com/ImageReplacement/1.0/',
'http://ns.adobe.com/GenericCustomNamespace/1.0/',
'http://ns.adobe.com/XPath/1.0/'
'http://ns.adobe.com/XPath/1.0/',
'http://schemas.microsoft.com/visio/2003/SVGExtensions/',
'http://taptrix.com/vectorillustrator/svg_extensions',
'http://www.figma.com/figma/ns',
'http://purl.org/dc/elements/1.1/',
'http://creativecommons.org/ns#',
'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'http://www.serif.com/',
'http://www.vector.evaxdesign.sk'
];
// http://www.w3.org/TR/SVG/linking.html#processingIRI
// http://www.w3.org/TR/SVG11/linking.html#processingIRI
exports.referencesProps = [
'clip-path',
'color-profile',
@@ -2296,7 +2304,7 @@ exports.referencesProps = [
'style'
];
// http://www.w3.org/TR/SVG/propidx.html
// http://www.w3.org/TR/SVG11/propidx.html
exports.inheritableAttrs = [
'clip-rule',
'color',
@@ -2306,6 +2314,7 @@ exports.inheritableAttrs = [
'color-rendering',
'cursor',
'direction',
'dominant-baseline',
'fill',
'fill-opacity',
'fill-rule',
@@ -2320,12 +2329,12 @@ exports.inheritableAttrs = [
'glyph-orientation-horizontal',
'glyph-orientation-vertical',
'image-rendering',
'kerning',
'letter-spacing',
'marker',
'marker-end',
'marker-mid',
'marker-start',
'paint-order',
'pointer-events',
'shape-rendering',
'stroke',
@@ -2340,12 +2349,23 @@ exports.inheritableAttrs = [
'text-rendering',
'transform',
'visibility',
'white-space',
'word-spacing',
'writing-mode'
];
// http://www.w3.org/TR/SVG/single-page.html#types-ColorKeywords
exports.presentationNonInheritableGroupAttrs = [
'display',
'clip-path',
'filter',
'mask',
'opacity',
'text-decoration',
'transform',
'unicode-bidi',
'visibility'
];
// http://www.w3.org/TR/SVG11/single-page.html#types-ColorKeywords
exports.colorsNames = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
@@ -2373,6 +2393,7 @@ exports.colorsNames = {
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkgrey': '#a9a9a9',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
@@ -2383,11 +2404,13 @@ exports.colorsNames = {
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
@@ -2400,6 +2423,7 @@ exports.colorsNames = {
'gray': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'grey': '#808080',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
@@ -2414,6 +2438,7 @@ exports.colorsNames = {
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
@@ -2421,6 +2446,7 @@ exports.colorsNames = {
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#789',
'lightslategrey': '#789',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#0f0',
@@ -2460,6 +2486,7 @@ exports.colorsNames = {
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'rebeccapurple': '#639',
'red': '#f00',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
@@ -2473,6 +2500,7 @@ exports.colorsNames = {
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
@@ -2512,6 +2540,7 @@ exports.colorsShortNames = {
'#dda0dd': 'plum',
'#800080': 'purple',
'#f00': 'red',
'#ff0000': 'red',
'#fa8072': 'salmon',
'#a0522d': 'sienna',
'#c0c0c0': 'silver',
@@ -2523,7 +2552,7 @@ exports.colorsShortNames = {
'#f5deb3': 'wheat'
};
// http://www.w3.org/TR/SVG/single-page.html#types-DataTypeColor
// http://www.w3.org/TR/SVG11/single-page.html#types-DataTypeColor
exports.colorsProps = [
'color', 'fill', 'stroke', 'stop-color', 'flood-color', 'lighting-color'
];

58
node_modules/svgo/plugins/_path.js generated vendored
View File

@@ -1,8 +1,16 @@
/* global a2c */
'use strict';
var rNumber = String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?\s*`,
rCommaWsp = String.raw`(?:\s,?\s*|,\s*)`,
rNumberCommaWsp = `(${rNumber})` + rCommaWsp,
rFlagCommaWsp = `([01])${rCommaWsp}?`,
rCoordinatePair = String.raw`(${rNumber})${rCommaWsp}?(${rNumber})`,
rArcSeq = (rNumberCommaWsp + '?').repeat(2) + rNumberCommaWsp + rFlagCommaWsp.repeat(2) + rCoordinatePair;
var regPathInstructions = /([MmLlHhVvCcSsQqTtAaZz])\s*/,
regPathData = /[-+]?(?:\d*\.\d+|\d+\.?)([eE][-+]?\d+)?/g,
regCoordinateSequence = new RegExp(rNumber, 'g'),
regArcArgumentSequence = new RegExp(rArcSeq, 'g'),
regNumericValues = /[-+]?(\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/,
transform2js = require('./_transforms').transform2js,
transformsMultiply = require('./_transforms').transformsMultiply,
@@ -53,11 +61,21 @@ exports.path2js = function(path) {
}
// data item
} else {
data = data.match(regPathData);
/* jshint boss: true */
if (instruction == 'A' || instruction == 'a') {
var newData = [];
for (var args; (args = regArcArgumentSequence.exec(data));) {
for (var i = 1; i < args.length; i++) {
newData.push(args[i]);
}
}
data = newData;
} else {
data = data.match(regCoordinateSequence);
}
if (!data) return;
data = data.map(Number);
// Subsequent moveto pairs of coordinates are threated as implicit lineto commands
// http://www.w3.org/TR/SVG/paths.html#PathDataMovetoCommands
if (instruction == 'M' || instruction == 'm') {
@@ -97,7 +115,7 @@ var relative2absolute = exports.relative2absolute = function(data) {
subpathPoint = [0, 0],
i;
data = data.map(function(item) {
return data.map(function(item) {
var instruction = item.instruction,
itemData = item.data && item.data.slice();
@@ -160,8 +178,6 @@ var relative2absolute = exports.relative2absolute = function(data) {
};
});
return data;
};
/**
@@ -210,16 +226,22 @@ exports.applyTransforms = function(elem, path, params) {
if (scale !== 1) {
var strokeWidth = elem.computedAttr('stroke-width') || defaultStrokeWidth;
if (elem.hasAttr('stroke-width')) {
elem.attrs['stroke-width'].value = elem.attrs['stroke-width'].value.trim()
.replace(regNumericValues, function(num) { return removeLeadingZero(num * scale) });
} else {
elem.addAttr({
name: 'stroke-width',
prefix: '',
local: 'stroke-width',
value: strokeWidth.replace(regNumericValues, function(num) { return removeLeadingZero(num * scale) })
});
if (!elem.hasAttr('vector-effect') || elem.attr('vector-effect').value !== 'non-scaling-stroke') {
if (elem.hasAttr('stroke-width')) {
elem.attrs['stroke-width'].value = elem.attrs['stroke-width'].value.trim()
.replace(regNumericValues, function(num) {
return removeLeadingZero(num * scale);
});
} else {
elem.addAttr({
name: 'stroke-width',
prefix: '',
local: 'stroke-width',
value: strokeWidth.replace(regNumericValues, function(num) {
return removeLeadingZero(num * scale);
})
});
}
}
}
} else if (id) { // Stroke and stroke-width can be redefined with <use>
@@ -754,7 +776,7 @@ function gatherPoints(points, item, index, path) {
prevCtrlPoint = [data[2] - data[0], data[3] - data[1]]; // Save control point for shorthand
break;
case 'T':
if (prev.instruction == 'Q' && prev.instruction == 'T') {
if (prev.instruction == 'Q' || prev.instruction == 'T') {
ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
addPoint(subPath, ctrlPoint);
prevCtrlPoint = [data[0] - ctrlPoint[0], data[1] - ctrlPoint[1]];
@@ -768,7 +790,7 @@ function gatherPoints(points, item, index, path) {
prevCtrlPoint = [data[4] - data[2], data[5] - data[3]]; // Save control point for shorthand
break;
case 'S':
if (prev.instruction == 'C' && prev.instruction == 'S') {
if (prev.instruction == 'C' || prev.instruction == 'S') {
addPoint(subPath, [basePoint[0] + .5 * prevCtrlPoint[0], basePoint[1] + .5 * prevCtrlPoint[1]]);
ctrlPoint = [basePoint[0] + prevCtrlPoint[0], basePoint[1] + prevCtrlPoint[1]];
}

View File

@@ -42,8 +42,8 @@ exports.transform2js = function(transformString) {
}
});
return transforms;
// return empty array if broken transform (no data)
return current && current.data ? transforms : [];
};
/**
@@ -65,9 +65,7 @@ exports.transformsMultiply = function(transforms) {
// multiply all matrices into one
transforms = {
name: 'matrix',
data: transforms.reduce(function(a, b) {
return multiplyTransformMatrices(a, b);
})
data: transforms.length > 0 ? transforms.reduce(multiplyTransformMatrices) : []
};
return transforms;
@@ -117,7 +115,7 @@ var mth = exports.mth = {
/**
* Decompose matrix into simple transforms. See
* http://www.maths-informatique-jeux.com/blog/frederic/?post/2013/12/01/Decomposition-of-2D-transform-matrices
* http://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
*
* @param {Object} data matrix transform object
* @return {Object|Array} transforms array or original transform object
@@ -126,11 +124,11 @@ exports.matrixToTransform = function(transform, params) {
var floatPrecision = params.floatPrecision,
data = transform.data,
transforms = [],
sx = +Math.sqrt(data[0] * data[0] + data[1] * data[1]).toFixed(params.transformPrecision),
sx = +Math.hypot(data[0], data[1]).toFixed(params.transformPrecision),
sy = +((data[0] * data[3] - data[1] * data[2]) / sx).toFixed(params.transformPrecision),
colsSum = data[0] * data[2] + data[1] * data[3],
rowsSum = data[0] * data[1] + data[2] * data[3],
scaleBefore = rowsSum || +(sx == sy);
scaleBefore = rowsSum != 0 || sx == sy;
// [..., ..., ..., ..., tx, ty] → translate(tx, ty)
if (data[4] || data[5]) {
@@ -151,11 +149,11 @@ exports.matrixToTransform = function(transform, params) {
// [sx·cos(a), sy·sin(a), sx·-sin(a), sy·cos(a), x, y] → scale(sx, sy)·rotate(a[, cx, cy]) (if !scaleBefore)
} else if (!colsSum || (sx == 1 && sy == 1) || !scaleBefore) {
if (!scaleBefore) {
sx = (data[0] < 0 ? -1 : 1) * Math.sqrt(data[0] * data[0] + data[2] * data[2]);
sy = (data[3] < 0 ? -1 : 1) * Math.sqrt(data[1] * data[1] + data[3] * data[3]);
sx = (data[0] < 0 ? -1 : 1) * Math.hypot(data[0], data[2]);
sy = (data[3] < 0 ? -1 : 1) * Math.hypot(data[1], data[3]);
transforms.push({ name: 'scale', data: [sx, sy] });
}
var rotate = [mth.acos(data[0] / sx, floatPrecision) * (data[1] * sy < 0 ? -1 : 1)];
var rotate = [mth.acos(data[0] / sx, floatPrecision) * ((scaleBefore ? 1 : sy) * data[1] < 0 ? -1 : 1)];
if (rotate[0]) transforms.push({ name: 'rotate', data: rotate });
@@ -262,10 +260,7 @@ exports.transformArc = function(arc, transform) {
// Decompose the new ellipse matrix
lastCol = m[2] * m[2] + m[3] * m[3],
squareSum = m[0] * m[0] + m[1] * m[1] + lastCol,
root = Math.sqrt(
(Math.pow(m[0] - m[3], 2) + Math.pow(m[1] + m[2], 2)) *
(Math.pow(m[0] + m[3], 2) + Math.pow(m[1] - m[2], 2))
);
root = Math.hypot(m[0] - m[3], m[1] + m[2]) * Math.hypot(m[0] + m[3], m[1] - m[2]);
if (!root) { // circle
arc[0] = arc[1] = Math.sqrt(squareSum / 2);
@@ -281,8 +276,14 @@ exports.transformArc = function(arc, transform) {
arc[0] = Math.sqrt(majorAxisSqr);
arc[1] = Math.sqrt(minorAxisSqr);
arc[2] = ((major ? term2 < 0 : term1 > 0) ? -1 : 1) *
Math.acos((major ? term1 : term2) / Math.sqrt(term1 * term1 + term2 * term2)) * 180 / Math.PI;
Math.acos((major ? term1 : term2) / Math.hypot(term1, term2)) * 180 / Math.PI;
}
if ((transform[0] < 0) !== (transform[3] < 0)) {
// Flip the sweep flag if coordinates are being flipped horizontally XOR vertically
arc[4] = 1 - arc[4];
}
return arc;
};

View File

@@ -6,17 +6,23 @@ exports.active = false;
exports.description = 'adds attributes to an outer <svg> element';
var ENOCLS = 'Error in plugin "addAttributesToSVGElement": absent parameters.\n\
It should have a list of classes in "attributes" or one "attribute".\n\
Config example:\n\n\
\
plugins:\n\
- addAttributesToSVGElement:\n\
attribute: "mySvg"\n\n\
\
plugins:\n\
- addAttributesToSVGElement:\n\
attributes: ["mySvg", "size-big"]\n';
var ENOCLS = `Error in plugin "addAttributesToSVGElement": absent parameters.
It should have a list of "attributes" or one "attribute".
Config example:
plugins:
- addAttributesToSVGElement:
attribute: "mySvg"
plugins:
- addAttributesToSVGElement:
attributes: ["mySvg", "size-big"]
plugins:
- addAttributesToSVGElement:
attributes:
- focusable: false
- data-image: icon`;
/**
* Add attributes to an outer <svg> element. Example config:
@@ -29,10 +35,16 @@ plugins:\n\
* - addAttributesToSVGElement:
* attributes: ['data-icon', 'data-disabled']
*
* plugins:
* - addAttributesToSVGElement:
* attributes:
* - focusable: false
* - data-image: icon
*
* @author April Arcus
*/
exports.fn = function(data, params) {
if (!params || !(Array.isArray(params.attributes) && params.attributes.some(String) || params.attribute)) {
if (!params || !(Array.isArray(params.attributes) || params.attribute)) {
console.error(ENOCLS);
return data;
}
@@ -42,11 +54,24 @@ exports.fn = function(data, params) {
if (svg.isElem('svg')) {
attributes.forEach(function (attribute) {
if (!svg.hasAttr(attribute)) {
svg.addAttr({
name: attribute,
prefix: '',
local: attribute
if (typeof attribute === 'string') {
if (!svg.hasAttr(attribute)) {
svg.addAttr({
name: attribute,
prefix: '',
local: attribute
});
}
} else if (typeof attribute === 'object') {
Object.keys(attribute).forEach(function (key) {
if (!svg.hasAttr(key)) {
svg.addAttr({
name: key,
value: attribute[key],
prefix: '',
local: key
});
}
});
}
});

View File

@@ -6,17 +6,18 @@ exports.active = false;
exports.description = 'adds classnames to an outer <svg> element';
var ENOCLS = 'Error in plugin "addClassesToSVGElement": absent parameters.\n\
It should have a list of classes in "classNames" or one "className".\n\
Config example:\n\n\
\
plugins:\n\
- addClassesToSVGElement:\n\
className: "mySvg"\n\n\
\
plugins:\n\
- addClassesToSVGElement:\n\
classNames: ["mySvg", "size-big"]\n';
var ENOCLS = `Error in plugin "addClassesToSVGElement": absent parameters.
It should have a list of classes in "classNames" or one "className".
Config example:
plugins:
- addClassesToSVGElement:
className: "mySvg"
plugins:
- addClassesToSVGElement:
classNames: ["mySvg", "size-big"]
`;
/**
* Add classnames to an outer <svg> element. Example config:
@@ -41,22 +42,7 @@ exports.fn = function(data, params) {
svg = data.content[0];
if (svg.isElem('svg')) {
if (svg.hasAttr('class')) {
var classes = svg.attr('class').value.split(' ');
classNames.forEach(function(className){
if (classes.indexOf(className) < 0) {
classes.push(className);
}
});
svg.attr('class').value = classes.join(' ');
} else {
svg.addAttr({
name: 'class',
value: classNames.join(' '),
prefix: '',
local: 'class'
});
}
svg.class.add.apply(svg.class, classNames);
}
return data;

View File

@@ -9,13 +9,16 @@ exports.description = 'removes unused IDs and minifies used';
exports.params = {
remove: true,
minify: true,
prefix: ''
prefix: '',
preserve: [],
preservePrefixes: [],
force: false
};
var referencesProps = require('./_collections').referencesProps,
var referencesProps = new Set(require('./_collections').referencesProps),
regReferencesUrl = /\burl\(("|')?#(.+?)\1\)/,
regReferencesHref = /^#(.+?)$/,
regReferencesBegin = /^(\w+?)\./,
regReferencesBegin = /(\w+)\./,
styleOrScript = ['style', 'script'],
generateIDchars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
@@ -33,13 +36,15 @@ var referencesProps = require('./_collections').referencesProps,
* @author Kir Belevich
*/
exports.fn = function(data, params) {
var currentID,
currentIDstring,
IDs = Object.create(null),
referencesIDs = Object.create(null),
idPrefix = 'id-', // prefix IDs so that values like '__proto__' don't break the work
hasStyleOrScript = false;
IDs = new Map(),
referencesIDs = new Map(),
hasStyleOrScript = false,
preserveIDs = new Set(Array.isArray(params.preserve) ? params.preserve : params.preserve ? [params.preserve] : []),
preserveIDPrefixes = new Set(Array.isArray(params.preservePrefixes) ? params.preservePrefixes : (params.preservePrefixes ? [params.preservePrefixes] : [])),
idValuePrefix = '#',
idValuePostfix = '.';
/**
* Bananas!
@@ -48,71 +53,66 @@ exports.fn = function(data, params) {
* @return {Array} output items
*/
function monkeys(items) {
for (var i = 0; i < items.content.length && !hasStyleOrScript; i++) {
var item = items.content[i];
var item = items.content[i],
match;
// check if <style> of <script> presents
if (item.isElem(styleOrScript)) {
hasStyleOrScript = true;
continue;
// quit if <style> or <script> present ('force' param prevents quitting)
if (!params.force) {
if (item.isElem(styleOrScript)) {
hasStyleOrScript = true;
continue;
}
// Don't remove IDs if the whole SVG consists only of defs.
if (item.isElem('defs') && item.parentNode.isElem('svg')) {
var hasDefsOnly = true;
for (var j = i + 1; j < items.content.length; j++) {
if (items.content[j].isElem()) {
hasDefsOnly = false;
break;
}
}
if (hasDefsOnly) {
break;
}
}
}
// …and don't remove any ID if yes
if (item.isElem()) {
item.eachAttr(function(attr) {
var key;
var key, match;
// save IDs
if (attr.name === 'id') {
key = idPrefix + attr.value;
if (key in IDs) {
item.removeAttr('id');
key = attr.value;
if (IDs.has(key)) {
item.removeAttr('id'); // remove repeated id
} else {
IDs[key] = item;
IDs.set(key, item);
}
return;
}
// save IDs url() references
else if (referencesProps.indexOf(attr.name) > -1) {
match = attr.value.match(regReferencesUrl);
if (match) {
key = idPrefix + match[2];
if (referencesIDs[key]) {
referencesIDs[key].push(attr);
} else {
referencesIDs[key] = [attr];
}
}
}
// save IDs href references
else if (
// save references
if (referencesProps.has(attr.name) && (match = attr.value.match(regReferencesUrl))) {
key = match[2]; // url() reference
} else if (
attr.local === 'href' && (match = attr.value.match(regReferencesHref)) ||
attr.name === 'begin' && (match = attr.value.match(regReferencesBegin))
) {
key = idPrefix + match[1];
if (referencesIDs[key]) {
referencesIDs[key].push(attr);
} else {
referencesIDs[key] = [attr];
}
key = match[1]; // href reference
}
if (key) {
var ref = referencesIDs.get(key) || [];
ref.push(attr);
referencesIDs.set(key, ref);
}
});
}
// go deeper
if (item.content) {
monkeys(item);
}
}
return items;
}
data = monkeys(data);
@@ -121,43 +121,50 @@ exports.fn = function(data, params) {
return data;
}
var idKey;
for (var k in referencesIDs) {
if (IDs[k]) {
idKey = k;
k = k.replace(idPrefix, '');
for (var ref of referencesIDs) {
var key = ref[0];
if (IDs.has(key)) {
// replace referenced IDs with the minified ones
if (params.minify) {
if (params.minify && !preserveIDs.has(key) && !idMatchesPrefix(preserveIDPrefixes, key)) {
currentIDstring = getIDstring(currentID = generateID(currentID), params);
IDs[idKey].attr('id').value = currentIDstring;
IDs.get(key).attr('id').value = currentIDstring;
referencesIDs[idKey].forEach(function(attr) {
attr.value = attr.value
.replace('#' + k, '#' + currentIDstring)
.replace(k + '.', currentIDstring + '.');
});
idKey = idPrefix + k;
for (var attr of ref[1]) {
attr.value = attr.value.includes(idValuePrefix) ?
attr.value.replace(idValuePrefix + key, idValuePrefix + currentIDstring) :
attr.value.replace(key + idValuePostfix, currentIDstring + idValuePostfix);
}
}
// don't remove referenced IDs
delete IDs[idKey];
IDs.delete(key);
}
}
// remove non-referenced IDs attributes from elements
if (params.remove) {
for(var ID in IDs) {
IDs[ID].removeAttr('id');
for(var keyElem of IDs) {
if (!preserveIDs.has(keyElem[0]) && !idMatchesPrefix(preserveIDPrefixes, keyElem[0])) {
keyElem[1].removeAttr('id');
}
}
}
return data;
};
/**
* Check if an ID starts with any one of a list of strings.
*
* @param {Array} of prefix strings
* @param {String} current ID
* @return {Boolean} if currentID starts with one of the strings in prefixArray
*/
function idMatchesPrefix(prefixArray, currentID) {
if (!currentID) return false;
for (var prefix of prefixArray) if (currentID.startsWith(prefix)) return true;
return false;
}
/**
* Generate unique minimal ID.
*
@@ -165,7 +172,6 @@ exports.fn = function(data, params) {
* @return {Array} generated ID array
*/
function generateID(currentID) {
if (!currentID) return [0];
currentID[currentID.length - 1]++;
@@ -179,14 +185,11 @@ function generateID(currentID) {
}
}
}
if (currentID[0] > maxIDindex) {
currentID[0] = 0;
currentID.unshift(0);
}
return currentID;
}
/**
@@ -196,13 +199,6 @@ function generateID(currentID) {
* @return {String} output ID string
*/
function getIDstring(arr, params) {
var str = params.prefix;
arr.forEach(function(i) {
str += generateIDchars[i];
});
return str;
return str + arr.map(i => generateIDchars[i]).join('');
}

View File

@@ -96,8 +96,7 @@ exports.fn = function(item, params) {
matchNew = elem.match(/new/);
// if attribute value matches regNumericValues
if(match){
if (match) {
// round it to the fixed precision
num = +(+match[1]).toFixed(params.floatPrecision),
units = match[3] || '';
@@ -122,13 +121,12 @@ exports.fn = function(item, params) {
}
roundedListArr.push(num+units);
}
// if attribute value is "new"(only enable-background).
else if(matchNew){
else if (matchNew) {
roundedListArr.push('new');
} else if (elem) {
roundedListArr.push(elem);
}
});

View File

@@ -37,24 +37,36 @@ exports.fn = function(item, params) {
if (item.isElem()) {
var match;
var floatPrecision = params.floatPrecision;
if (item.hasAttr('viewBox')) {
var nums = item.attr('viewBox').value.split(/\s,?\s*|,\s*/g);
item.attr('viewBox').value = nums.map(function(value) {
var num = +value;
return isNaN(num) ? value : +num.toFixed(floatPrecision);
}).join(' ');
}
item.eachAttr(function(attr) {
match = attr.value.match(regNumericValues);
// The `version` attribute is a text string and cannot be rounded
if (attr.name === 'version') { return }
var match = attr.value.match(regNumericValues);
// if attribute value matches regNumericValues
if (match) {
// round it to the fixed precision
var num = +(+match[1]).toFixed(params.floatPrecision),
var num = +(+match[1]).toFixed(floatPrecision),
units = match[3] || '';
// convert absolute values to pixels
if (params.convertToPx && units && (units in absoluteLengths)) {
var pxNum = +(absoluteLengths[units] * match[1]).toFixed(params.floatPrecision);
var pxNum = +(absoluteLengths[units] * match[1]).toFixed(floatPrecision);
if (String(pxNum).length < match[0].length)
num = pxNum,
if (String(pxNum).length < match[0].length) {
num = pxNum;
units = 'px';
}
}
// and remove leading zero

View File

@@ -43,17 +43,14 @@ exports.fn = function(item) {
// non-empty elements
if (item.isElem() && !item.isElem('switch') && !item.isEmpty()) {
item.content.forEach(function(g, i) {
// non-empty groups
if (g.isElem('g') && !g.isEmpty()) {
// move group attibutes to the single content element
if (g.hasAttr() && g.content.length === 1) {
var inner = g.content[0];
if (inner.isElem() && !inner.hasAttr('id') &&
if (inner.isElem() && !inner.hasAttr('id') && !g.hasAttr('filter') &&
!(g.hasAttr('class') && inner.hasAttr('class')) && (
!g.hasAttr('clip-path') && !g.hasAttr('mask') ||
inner.isElem('g') && !g.hasAttr('transform') && !inner.hasAttr('transform')
@@ -66,6 +63,8 @@ exports.fn = function(item) {
inner.addAttr(attr);
} else if (attr.name == 'transform') {
inner.attr(attr.name).value = attr.value + ' ' + inner.attr(attr.name).value;
} else if (inner.hasAttr(attr.name, 'inherit')) {
inner.attr(attr.name).value = attr.value;
} else if (
attrsInheritable.indexOf(attr.name) < 0 &&
!inner.hasAttr(attr.name, attr.value)
@@ -83,9 +82,6 @@ exports.fn = function(item) {
item.spliceContent(i, 1, g.content);
}
}
});
}
};

View File

@@ -95,8 +95,11 @@ exports.fn = function(item, params) {
}
// Convert hex to short name
if (params.shortname && val in collections.colorsShortNames) {
val = collections.colorsShortNames[val];
if (params.shortname) {
var lowerVal = val.toLowerCase();
if (lowerVal in collections.colorsShortNames) {
val = collections.colorsShortNames[lowerVal];
}
}
attr.value = val;

View File

@@ -22,7 +22,8 @@ exports.params = {
collapseRepeated: true,
utilizeAbsolute: true,
leadingZero: true,
negativeExtraSpace: true
negativeExtraSpace: true,
forceAbsolutePath: false
};
var pathElems = require('./_collections.js').pathElems,
@@ -35,7 +36,8 @@ var pathElems = require('./_collections.js').pathElems,
error,
arcThreshold,
arcTolerance,
hasMarkerMid;
hasMarkerMid,
hasStrokeLinecap;
/**
* Convert absolute Path to relative,
@@ -66,6 +68,10 @@ exports.fn = function(item, params) {
}
hasMarkerMid = item.hasAttr('marker-mid');
var stroke = item.computedAttr('stroke'),
strokeLinecap = item.computedAttr('stroke');
hasStrokeLinecap = stroke && stroke != 'none' && strokeLinecap && strokeLinecap != 'butt';
var data = path2js(item);
// TODO: get rid of functions returns
@@ -583,7 +589,7 @@ function filters(path, params) {
}
// remove useless non-first path segments
if (params.removeUseless) {
if (params.removeUseless && !hasStrokeLinecap) {
// l 0,0 / h 0 / v 0 / q 0,0 0,0 / t 0,0 / c 0,0 0,0 0,0 / s 0,0 0,0
if (
@@ -671,11 +677,12 @@ function convertToMixed(path, params) {
var absoluteDataStr = cleanupOutData(adata, params),
relativeDataStr = cleanupOutData(data, params);
// Convert to absolute coordinates if it's shorter.
// Convert to absolute coordinates if it's shorter or forceAbsolutePath is true.
// v-20 -> V0
// Don't convert if it fits following previous instruction.
// l20 30-10-50 instead of l20 30L20 30
if (
params.forceAbsolutePath || (
absoluteDataStr.length < relativeDataStr.length &&
!(
params.negativeExtraSpace &&
@@ -683,7 +690,7 @@ function convertToMixed(path, params) {
prev.instruction.charCodeAt(0) > 96 &&
absoluteDataStr.length == relativeDataStr.length - 1 &&
(data[0] < 0 || /^0\./.test(data[0]) && prev.data[prev.data.length - 1] % 1)
)
))
) {
item.instruction = instruction.toUpperCase();
item.data = adata;
@@ -840,7 +847,7 @@ function makeLonghand(item, data) {
*/
function getDistance(point1, point2) {
return Math.sqrt(Math.pow(point1[0] - point2[0], 2) + Math.pow(point1[1] - point2[1], 2));
return Math.hypot(point1[0] - point2[0], point1[1] - point2[1]);
}
/**
@@ -885,21 +892,22 @@ function findCircle(curve) {
radius = center && getDistance([0, 0], center),
tolerance = Math.min(arcThreshold * error, arcTolerance * radius / 100);
if (center && [1/4, 3/4].every(function(point) {
if (center && radius < 1e15 &&
[1/4, 3/4].every(function(point) {
return Math.abs(getDistance(getCubicBezierPoint(curve, point), center) - radius) <= tolerance;
}))
return { center: center, radius: radius};
}
/**
* Checks if a curve fits the given circe.
* Checks if a curve fits the given circle.
*
* @param {Object} circle
* @param {Array} curve
* @return {Boolean}
*/
function isArc(curve, circle) {
function isArc(curve, circle) {
var tolerance = Math.min(arcThreshold * error, arcTolerance * circle.radius / 100);
return [0, 1/4, 1/2, 3/4, 1].every(function(point) {
@@ -908,14 +916,14 @@ function isArc(curve, circle) {
}
/**
* Checks if a previos curve fits the given circe.
* Checks if a previous curve fits the given circle.
*
* @param {Object} circle
* @param {Array} curve
* @return {Boolean}
*/
function isArcPrev(curve, circle) {
function isArcPrev(curve, circle) {
return isArc(curve, {
center: [circle.center[0] + curve[4], circle.center[1] + curve[5]],
radius: circle.radius
@@ -952,6 +960,6 @@ function findArcAngle(curve, relCircle) {
function data2Path(params, pathData) {
return pathData.reduce(function(pathString, item) {
return pathString += item.instruction + (item.data ? cleanupOutData(roundData(item.data.slice()), params) : '');
return pathString + item.instruction + (item.data ? cleanupOutData(roundData(item.data.slice()), params) : '');
}, '');
}

View File

@@ -6,6 +6,10 @@ exports.active = true;
exports.description = 'converts basic shapes to more compact path form';
exports.params = {
convertArcs: false
};
var none = { value: 0 },
regNumber = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
@@ -22,7 +26,8 @@ var none = { value: 0 },
*
* @author Lev Solntsev
*/
exports.fn = function(item) {
exports.fn = function(item, params) {
var convertArcs = params && params.convertArcs;
if (
item.isElem('rect') &&
@@ -98,6 +103,47 @@ exports.fn = function(item) {
item.renameElem('path')
.removeAttr('points');
}
} else if (item.isElem('circle') && convertArcs) {
var cx = +(item.attr('cx') || none).value;
var cy = +(item.attr('cy') || none).value;
var r = +(item.attr('r') || none).value;
if (isNaN(cx - cy + r)) {
return;
}
var cPathData =
'M' + cx + ' ' + (cy - r) +
'A' + r + ' ' + r + ' 0 1 0 ' + cx + ' ' + (cy + r) +
'A' + r + ' ' + r + ' 0 1 0 ' + cx + ' ' + (cy - r) +
'Z';
item.addAttr({
name: 'd',
value: cPathData,
prefix: '',
local: 'd',
});
item.renameElem('path').removeAttr(['cx', 'cy', 'r']);
} else if (item.isElem('ellipse') && convertArcs) {
var ecx = +(item.attr('cx') || none).value;
var ecy = +(item.attr('cy') || none).value;
var rx = +(item.attr('rx') || none).value;
var ry = +(item.attr('ry') || none).value;
if (isNaN(ecx - ecy + rx - ry)) {
return;
}
var ePathData =
'M' + ecx + ' ' + (ecy - ry) +
'A' + rx + ' ' + ry + ' 0 1 0 ' + ecx + ' ' + (ecy + ry) +
'A' + rx + ' ' + ry + ' 0 1 0 ' + ecx + ' ' + (ecy - ry) +
'Z';
item.addAttr({
name: 'd',
value: ePathData,
prefix: '',
local: 'd',
});
item.renameElem('path').removeAttr(['cx', 'cy', 'rx', 'ry']);
}
};

View File

@@ -7,8 +7,11 @@ exports.active = true;
exports.description = 'converts style to attributes';
var EXTEND = require('whet.extend'),
stylingProps = require('./_collections').attrsGroups.presentation,
exports.params = {
keepImportant: false
};
var stylingProps = require('./_collections').attrsGroups.presentation,
rEscape = '\\\\(?:[0-9a-f]{1,6}\\s?|\\r\\n|.)', // Like \" or \2051. Code points consume one space.
rAttr = '\\s*(' + g('[^:;\\\\]', rEscape) + '*?)\\s*', // attribute name like fill
rSingleQuotes = "'(?:[^'\\n\\r\\\\]|" + rEscape + ")*?(?:'|$)", // string in single quotes: 'smth'
@@ -20,13 +23,16 @@ var EXTEND = require('whet.extend'),
rParenthesis = '\\(' + g('[^\'"()\\\\]+', rEscape, rSingleQuotes, rQuotes) + '*?' + '\\)',
// The value. It can have strings and parentheses (see above). Fallbacks to anything in case of unexpected input.
rValue = '\\s*(' + g('[^\'"();\\\\]+?', rEscape, rSingleQuotes, rQuotes, rParenthesis, '[^;]*?') + '*?' + ')',
rValue = '\\s*(' + g('[^!\'"();\\\\]+?', rEscape, rSingleQuotes, rQuotes, rParenthesis, '[^;]*?') + '*?' + ')',
// End of declaration. Spaces outside of capturing groups help to do natural trimming.
rDeclEnd = '\\s*(?:;\\s*|$)',
// Important rule
rImportant = '(\\s*!important(?![-(\w]))?',
// Final RegExp to parse CSS declarations.
regDeclarationBlock = new RegExp(rAttr + ':' + rValue + rDeclEnd, 'ig'),
regDeclarationBlock = new RegExp(rAttr + ':' + rValue + rImportant + rDeclEnd, 'ig'),
// Comments expression. Honors escape sequences and strings.
regStripComments = new RegExp(g(rEscape, rSingleQuotes, rQuotes, '/\\*[^]*?\\*/'), 'ig');
@@ -49,7 +55,7 @@ var EXTEND = require('whet.extend'),
*
* @author Kir Belevich
*/
exports.fn = function(item) {
exports.fn = function(item, params) {
/* jshint boss: true */
if (item.elem && item.hasAttr('style')) {
@@ -66,7 +72,9 @@ exports.fn = function(item) {
regDeclarationBlock.lastIndex = 0;
for (var rule; rule = regDeclarationBlock.exec(styleValue);) {
styles.push([rule[1], rule[2]]);
if (!params.keepImportant || !rule[3]) {
styles.push([rule[1], rule[2]]);
}
}
if (styles.length) {
@@ -96,7 +104,7 @@ exports.fn = function(item) {
return true;
});
EXTEND(item.attrs, attrs);
Object.assign(item.attrs, attrs);
if (styles.length) {
item.attr('style').value = styles

View File

@@ -22,7 +22,6 @@ exports.params = {
};
var cleanupOutData = require('../lib/svgo/tools').cleanupOutData,
EXTEND = require('whet.extend'),
transform2js = require('./_transforms.js').transform2js,
transformsMultiply = require('./_transforms.js').transformsMultiply,
matrixToTransform = require('./_transforms.js').matrixToTransform,
@@ -116,7 +115,7 @@ function definePrecision(data, params) {
significantDigits = params.transformPrecision;
// Clone params so it don't affect other elements transformations.
params = EXTEND({}, params);
params = Object.assign({}, params);
// Limit transform precision with matrix one. Calculating with larger precision doesn't add any value.
if (matrixData.length) {

View File

@@ -1,45 +1,160 @@
'use strict';
exports.type = 'perItem';
exports.type = 'full';
exports.active = true;
exports.params = {
svgo: {}
};
exports.description = 'minifies styles and removes unused styles based on usage data';
exports.description = 'minifies existing styles in svg';
exports.params = {
// ... CSSO options goes here
// additional
usage: {
force: false, // force to use usage data even if it unsafe (document contains <script> or on* attributes)
ids: true,
classes: true,
tags: true
}
};
var csso = require('csso');
/**
* Minifies styles (<style> element + style attribute) using svgo
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
* Minifies styles (<style> element + style attribute) using CSSO
*
* @author strarsis <strarsis@gmail.com>
*/
exports.fn = function(item, svgoOptions) {
exports.fn = function(ast, options) {
options = options || {};
if(item.elem) {
if(item.isElem('style') && !item.isEmpty()) {
var styleCss = item.content[0].text || item.content[0].cdata || [],
DATA = styleCss.indexOf('>') >= 0 || styleCss.indexOf('<') >= 0 ? 'cdata' : 'text';
if(styleCss.length > 0) {
var styleCssMinified = csso.minify(styleCss, svgoOptions);
item.content[0][DATA] = styleCssMinified.css;
}
}
var minifyOptionsForStylesheet = cloneObject(options);
var minifyOptionsForAttribute = cloneObject(options);
var elems = findStyleElems(ast);
if(item.hasAttr('style')) {
var itemCss = item.attr('style').value;
if(itemCss.length > 0) {
var itemCssMinified = csso.minifyBlock(itemCss, svgoOptions);
item.attr('style').value = itemCssMinified.css;
}
}
minifyOptionsForStylesheet.usage = collectUsageData(ast, options);
minifyOptionsForAttribute.usage = null;
elems.forEach(function(elem) {
if (elem.isElem('style')) {
// <style> element
var styleCss = elem.content[0].text || elem.content[0].cdata || [];
var DATA = styleCss.indexOf('>') >= 0 || styleCss.indexOf('<') >= 0 ? 'cdata' : 'text';
elem.content[0][DATA] = csso.minify(styleCss, minifyOptionsForStylesheet).css;
} else {
// style attribute
var elemStyle = elem.attr('style').value;
elem.attr('style').value = csso.minifyBlock(elemStyle, minifyOptionsForAttribute).css;
}
});
return ast;
};
function cloneObject(obj) {
var result = {};
for (var key in obj) {
result[key] = obj[key];
}
return item;
};
return result;
}
function findStyleElems(ast) {
function walk(items, styles) {
for (var i = 0; i < items.content.length; i++) {
var item = items.content[i];
// go deeper
if (item.content) {
walk(item, styles);
}
if (item.isElem('style') && !item.isEmpty()) {
styles.push(item);
} else if (item.isElem() && item.hasAttr('style')) {
styles.push(item);
}
}
return styles;
}
return walk(ast, []);
}
function shouldFilter(options, name) {
if ('usage' in options === false) {
return true;
}
if (options.usage && name in options.usage === false) {
return true;
}
return Boolean(options.usage && options.usage[name]);
}
function collectUsageData(ast, options) {
function walk(items, usageData) {
for (var i = 0; i < items.content.length; i++) {
var item = items.content[i];
// go deeper
if (item.content) {
walk(item, usageData);
}
if (item.isElem('script')) {
safe = false;
}
if (item.isElem()) {
usageData.tags[item.elem] = true;
if (item.hasAttr('id')) {
usageData.ids[item.attr('id').value] = true;
}
if (item.hasAttr('class')) {
item.attr('class').value.replace(/^\s+|\s+$/g, '').split(/\s+/).forEach(function(className) {
usageData.classes[className] = true;
});
}
if (item.attrs && Object.keys(item.attrs).some(function(name) { return /^on/i.test(name); })) {
safe = false;
}
}
}
return usageData;
}
var safe = true;
var usageData = {};
var hasData = false;
var rawData = walk(ast, {
ids: Object.create(null),
classes: Object.create(null),
tags: Object.create(null)
});
if (!safe && options.usage && options.usage.force) {
safe = true;
}
for (var key in rawData) {
if (shouldFilter(options, key)) {
usageData[key] = Object.keys(rawData[key]);
hasData = true;
}
}
return safe && hasData ? usageData : null;
}

View File

@@ -1,6 +1,6 @@
'use strict';
var ELEM_SEP = ':';
var DEFAULT_SEPARATOR = ':';
exports.type = 'perItem';
@@ -9,18 +9,27 @@ exports.active = false;
exports.description = 'removes specified attributes';
exports.params = {
elemSeparator: DEFAULT_SEPARATOR,
preserveCurrentColor: false,
attrs: []
};
/**
* Remove attributes
*
* @param elemSeparator
* format: string
*
* @param preserveCurrentColor
* format: boolean
*
* @param attrs:
*
* format: [ element* : attribute* ]
* format: [ element* : attribute* : value* ]
*
* element : regexp (wrapped into ^...$), single * or omitted > all elements
* element : regexp (wrapped into ^...$), single * or omitted > all elements (must be present when value is used)
* attribute : regexp (wrapped into ^...$)
* value : regexp (wrapped into ^...$), single * or omitted > all values
*
* examples:
*
@@ -33,6 +42,10 @@ exports.params = {
* ---
* attrs: 'path:fill'
*
* > remove fill attribute on path element where value is none
* ---
* attrs: 'path:fill:none'
*
*
* > remove all fill and stroke attribute
* ---
@@ -52,6 +65,10 @@ exports.params = {
*
* attrs: '.*:(fill|stroke)'
*
* [is same as]
*
* attrs: '.*:(fill|stroke):.*'
*
*
* > remove all stroke related attributes
* ----
@@ -65,24 +82,29 @@ exports.params = {
* @author Benny Schudel
*/
exports.fn = function(item, params) {
// wrap into an array if params is not
if (!Array.isArray(params.attrs)) {
params.attrs = [params.attrs];
}
if (item.isElem()) {
var elemSeparator = typeof params.elemSeparator == 'string' ? params.elemSeparator : DEFAULT_SEPARATOR;
var preserveCurrentColor = typeof params.preserveCurrentColor == 'boolean' ? params.preserveCurrentColor : false;
// prepare patterns
var patterns = params.attrs.map(function(pattern) {
// apply to all elements if specifc element is omitted
if (pattern.indexOf(ELEM_SEP) === -1) {
pattern = ['.*', ELEM_SEP, pattern].join('');
// if no element separators (:), assume it's attribute name, and apply to all elements *regardless of value*
if (pattern.indexOf(elemSeparator) === -1) {
pattern = ['.*', elemSeparator, pattern, elemSeparator, '.*'].join('');
// if only 1 separator, assume it's element and attribute name, and apply regardless of attribute value
} else if (pattern.split(elemSeparator).length < 3) {
pattern = [pattern, elemSeparator, '.*'].join('');
}
// create regexps for element and attribute name
return pattern.split(ELEM_SEP)
// create regexps for element, attribute name, and attribute value
return pattern.split(elemSeparator)
.map(function(value) {
// adjust single * to match anything
@@ -102,10 +124,19 @@ exports.fn = function(item, params) {
// loop attributes
item.eachAttr(function(attr) {
var name = attr.name;
var value = attr.value;
var isFillCurrentColor = preserveCurrentColor && name == 'fill' && value == 'currentColor';
var isStrokeCurrentColor = preserveCurrentColor && name == 'stroke' && value == 'currentColor';
if (!(isFillCurrentColor || isStrokeCurrentColor)) {
// matches attribute name
if (pattern[1].test(name)) {
item.removeAttr(name);
if (pattern[1].test(name)) {
// matches attribute value
if (pattern[2].test(attr.value)) {
item.removeAttr(name);
}
}
}
});

View File

@@ -5,12 +5,12 @@ exports.type = 'perItem';
exports.active = true;
exports.params = {
removeAny: false
removeAny: true
};
exports.description = 'removes <desc> (only non-meaningful by default)';
exports.description = 'removes <desc>';
var standardDescs = /^Created with/;
var standardDescs = /^(Created with|Created using)/;
/**
* Removes <desc>.

View File

@@ -4,7 +4,7 @@ exports.type = 'perItem';
exports.active = false;
exports.description = 'removes width and height in presence of viewBox';
exports.description = 'removes width and height in presence of viewBox (opposite to removeViewBox, disable it first)';
/**
* Remove width/height attributes when a viewBox attribute is present.

View File

@@ -7,6 +7,7 @@ exports.active = true;
exports.description = 'removes hidden elements (zero sized, with absent attributes)';
exports.params = {
isHidden: true,
displayNone: true,
opacity0: true,
circleR0: true,
@@ -44,9 +45,15 @@ var regValidPath = /M\s*(?:[-+]?(?:\d*\.\d+|\d+(?:\.|(?!\.)))([eE][-+]?\d+)?(?!\
*
* @author Kir Belevich
*/
exports.fn = function(item, params) {
exports.fn = function (item, params) {
if (item.elem) {
// Removes hidden elements
// https://www.w3schools.com/cssref/pr_class_visibility.asp
if (
params.isHidden &&
item.hasAttr('visibility', 'hidden')
) return false;
// display="none"
//

View File

@@ -8,7 +8,7 @@ exports.description = 'removes non-inheritable groups presentational attribut
var inheritableAttrs = require('./_collections').inheritableAttrs,
attrsGroups = require('./_collections').attrsGroups,
excludedAttrs = ['display', 'opacity'];
applyGroups = require('./_collections').presentationNonInheritableGroupAttrs;
/**
* Remove non-inheritable group's "presentation" attributes.
@@ -25,11 +25,8 @@ exports.fn = function(item) {
item.eachAttr(function(attr) {
if (
~attrsGroups.presentation.indexOf(attr.name) &&
~attrsGroups.graphicalEvent.indexOf(attr.name) &&
~attrsGroups.core.indexOf(attr.name) &&
~attrsGroups.conditionalProcessing.indexOf(attr.name) &&
!~excludedAttrs.indexOf(attr.name) &&
!~inheritableAttrs.indexOf(attr.name)
!~inheritableAttrs.indexOf(attr.name) &&
!~applyGroups.indexOf(attr.name)
) {
item.removeAttr(attr.name);
}

View File

@@ -2,13 +2,12 @@
exports.type = 'perItem';
exports.active = false;
exports.active = true;
exports.description = 'removes <title> (disabled by default)';
exports.description = 'removes <title>';
/**
* Remove <title>.
* Disabled by default cause it may be used for accessibility.
*
* https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title
*

View File

@@ -11,7 +11,9 @@ exports.params = {
unknownAttrs: true,
defaultAttrs: true,
uselessOverrides: true,
keepDataAttrs: true
keepDataAttrs: true,
keepAriaAttrs: true,
keepRoleAttr: false
};
var collections = require('./_collections'),
@@ -19,7 +21,8 @@ var collections = require('./_collections'),
attrsGroups = collections.attrsGroups,
elemsGroups = collections.elemsGroups,
attrsGroupsDefaults = collections.attrsGroupsDefaults,
attrsInheritable = collections.inheritableAttrs;
attrsInheritable = collections.inheritableAttrs,
applyGroups = collections.presentationNonInheritableGroupAttrs;
// collect and extend all references
for (var elem in elems) {
@@ -105,7 +108,9 @@ exports.fn = function(item, params) {
if (
attr.name !== 'xmlns' &&
(attr.prefix === 'xml' || !attr.prefix) &&
(!params.keepDataAttrs || attr.name.indexOf('data-') != 0)
(!params.keepDataAttrs || attr.name.indexOf('data-') != 0) &&
(!params.keepAriaAttrs || attr.name.indexOf('aria-') != 0) &&
(!params.keepRoleAttr || attr.name != 'role')
) {
if (
// unknown attrs
@@ -116,6 +121,7 @@ exports.fn = function(item, params) {
// attrs with default values
(
params.defaultAttrs &&
!item.hasAttr('id') &&
elems[elem].defaults &&
elems[elem].defaults[attr.name] === attr.value && (
attrsInheritable.indexOf(attr.name) < 0 ||
@@ -125,7 +131,8 @@ exports.fn = function(item, params) {
// useless overrides
(
params.uselessOverrides &&
attr.name !== 'transform' &&
!item.hasAttr('id') &&
applyGroups.indexOf(attr.name) < 0 &&
attrsInheritable.indexOf(attr.name) > -1 &&
item.parentNode.computedAttr(attr.name, attr.value)
)

View File

@@ -6,8 +6,7 @@ exports.active = true;
exports.description = 'removes elements in <defs> without id';
var nonRendering = require('./_collections').elemsGroups.nonRendering,
defs;
var nonRendering = require('./_collections').elemsGroups.nonRendering;
/**
* Removes content of defs and properties that aren't rendered directly without ids.
@@ -21,9 +20,10 @@ exports.fn = function(item) {
if (item.isElem('defs')) {
defs = item;
item.content = (item.content || []).reduce(getUsefulItems, []);
if (item.content) {
item.content = getUsefulItems(item, []);
}
if (item.isEmpty()) return false;
} else if (item.isElem(nonRendering) && !item.hasAttr('id')) {
@@ -34,18 +34,20 @@ exports.fn = function(item) {
};
function getUsefulItems(usefulItems, item) {
function getUsefulItems(item, usefulItems) {
if (item.hasAttr('id') || item.isElem('style')) {
item.content.forEach(function(child) {
if (child.hasAttr('id') || child.isElem('style')) {
usefulItems.push(item);
item.parentNode = defs;
usefulItems.push(child);
child.parentNode = item;
} else if (!item.isEmpty()) {
} else if (!child.isEmpty()) {
item.content.reduce(getUsefulItems, usefulItems);
child.content = getUsefulItems(child, usefulItems);
}
}
});
return usefulItems;
}

View File

@@ -8,14 +8,15 @@ exports.description = 'removes useless stroke and fill attributes';
exports.params = {
stroke: true,
fill: true
fill: true,
removeNone: false,
hasStyleOrScript: false
};
var shape = require('./_collections').elemsGroups.shape,
regStrokeProps = /^stroke/,
regFillProps = /^fill-/,
styleOrScript = ['style', 'script'],
hasStyleOrScript = false;
styleOrScript = ['style', 'script'];
/**
* Remove useless stroke and fill attrs.
@@ -27,12 +28,12 @@ var shape = require('./_collections').elemsGroups.shape,
* @author Kir Belevich
*/
exports.fn = function(item, params) {
if (item.isElem(styleOrScript)) {
hasStyleOrScript = true;
params.hasStyleOrScript = true;
}
if (!hasStyleOrScript && item.isElem(shape) && !item.computedAttr('id')) {
if (!params.hasStyleOrScript && item.isElem(shape) && !item.computedAttr('id')) {
var stroke = params.stroke && item.computedAttr('stroke'),
fill = params.fill && !item.computedAttr('fill', 'none');
@@ -87,6 +88,13 @@ exports.fn = function(item, params) {
}
}
if (params.removeNone &&
(!stroke || item.hasAttr('stroke') && item.attr('stroke').value=='none') &&
(!fill || item.hasAttr('fill') && item.attr('fill').value=='none')) {
return false;
}
}
};

View File

@@ -2,12 +2,11 @@
exports.type = 'perItem';
exports.active = false;
exports.active = true;
exports.description = 'removes viewBox attribute when possible (disabled by default)';
exports.description = 'removes viewBox attribute when possible';
var regViewBox = /^0\s0\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)$/,
viewBoxElems = ['svg', 'pattern'];
var viewBoxElems = ['svg', 'pattern', 'symbol'];
/**
* Remove viewBox attr which coincides with a width/height box.
@@ -33,15 +32,15 @@ exports.fn = function(item) {
item.hasAttr('height')
) {
var match = item.attr('viewBox').value.match(regViewBox);
var nums = item.attr('viewBox').value.split(/[ ,]+/g);
if (match) {
if (
item.attr('width').value === match[1] &&
item.attr('height').value === match[3]
) {
item.removeAttr('viewBox');
}
if (
nums[0] === '0' &&
nums[1] === '0' &&
item.attr('width').value.replace(/px$/, '') === nums[2] && // could use parseFloat too
item.attr('height').value.replace(/px$/, '') === nums[3]
) {
item.removeAttr('viewBox');
}
}

View File

@@ -30,7 +30,8 @@ exports.fn = function(item, params) {
var attrs = [],
sorted = {},
orderlen = params.order.length + 1;
orderlen = params.order.length + 1,
xmlnsOrder = params.xmlnsOrder || 'front';
if (item.elem) {
@@ -41,10 +42,12 @@ exports.fn = function(item, params) {
attrs.sort(function(a, b) {
if (a.prefix != b.prefix) {
// xmlns attributes implicitly have the prefix xmlns
if (a.prefix == 'xmlns')
return -1;
if (b.prefix == 'xmlns')
return 1;
if (xmlnsOrder == 'front') {
if (a.prefix == 'xmlns')
return -1;
if (b.prefix == 'xmlns')
return 1;
}
return a.prefix < b.prefix ? -1 : 1;
}

View File

@@ -1,327 +0,0 @@
'use strict';
/*
* Thanks to http://fontello.com project for sponsoring this plugin
*/
exports.type = 'full';
exports.active = false;
exports.description = 'performs a set of operations on SVG with one path inside (disabled by default)';
exports.params = {
// width and height to resize SVG and rescale inner Path
width: false,
height: false,
// scale inner Path without resizing SVG
scale: false,
// shiftX/Y inner Path
shiftX: false,
shiftY: false,
// crop SVG width along the real width of inner Path
hcrop: false,
// vertical center inner Path inside SVG height
vcenter: false,
// stringify params
floatPrecision: 3,
leadingZero: true,
negativeExtraSpace: true
};
var _path = require('./_path.js'),
relative2absolute = _path.relative2absolute,
computeCubicBoundingBox = _path.computeCubicBoundingBox,
computeQuadraticBoundingBox = _path.computeQuadraticBoundingBox,
applyTransforms = _path.applyTransforms,
js2path = _path.js2path,
path2js = _path.path2js,
EXTEND = require('whet.extend');
exports.fn = function(data, params) {
data.content.forEach(function(item) {
// only for SVG with one Path inside
if (item.isElem('svg') &&
item.content.length === 1 &&
item.content[0].isElem('path')
) {
var svgElem = item,
pathElem = svgElem.content[0],
// get absoluted Path data
path = relative2absolute(EXTEND(true, [], path2js(pathElem))),
xs = [],
ys = [],
cubicСontrolPoint = [0, 0],
quadraticСontrolPoint = [0, 0],
lastPoint = [0, 0],
cubicBoundingBox,
quadraticBoundingBox,
i,
segment;
path.forEach(function(pathItem) {
// ML
if ('ML'.indexOf(pathItem.instruction) > -1) {
for (i = 0; i < pathItem.data.length; i++) {
if (i % 2 === 0) {
xs.push(pathItem.data[i]);
} else {
ys.push(pathItem.data[i]);
}
}
lastPoint = cubicСontrolPoint = quadraticСontrolPoint = pathItem.data.slice(-2);
// H
} else if (pathItem.instruction === 'H') {
pathItem.data.forEach(function(d) {
xs.push(d);
});
lastPoint[0] = cubicСontrolPoint[0] = quadraticСontrolPoint[0] = pathItem.data[pathItem.data.length - 2];
// V
} else if (pathItem.instruction === 'V') {
pathItem.data.forEach(function(d) {
ys.push(d);
});
lastPoint[1] = cubicСontrolPoint[1] = quadraticСontrolPoint[1] = pathItem.data[pathItem.data.length - 1];
// C
} else if (pathItem.instruction === 'C') {
for (i = 0; i < pathItem.data.length; i += 6) {
segment = pathItem.data.slice(i, i + 6);
cubicBoundingBox = computeCubicBoundingBox.apply(this, lastPoint.concat(segment));
xs.push(cubicBoundingBox.minx);
xs.push(cubicBoundingBox.maxx);
ys.push(cubicBoundingBox.miny);
ys.push(cubicBoundingBox.maxy);
// reflected control point for the next possible S
cubicСontrolPoint = [
2 * segment[4] - segment[2],
2 * segment[5] - segment[3]
];
lastPoint = segment.slice(-2);
}
// S
} else if (pathItem.instruction === 'S') {
for (i = 0; i < pathItem.data.length; i += 4) {
segment = pathItem.data.slice(i, i + 4);
cubicBoundingBox = computeCubicBoundingBox.apply(this, lastPoint.concat(cubicСontrolPoint).concat(segment));
xs.push(cubicBoundingBox.minx);
xs.push(cubicBoundingBox.maxx);
ys.push(cubicBoundingBox.miny);
ys.push(cubicBoundingBox.maxy);
// reflected control point for the next possible S
cubicСontrolPoint = [
2 * segment[2] - cubicСontrolPoint[0],
2 * segment[3] - cubicСontrolPoint[1],
];
lastPoint = segment.slice(-2);
}
// Q
} else if (pathItem.instruction === 'Q') {
for (i = 0; i < pathItem.data.length; i += 4) {
segment = pathItem.data.slice(i, i + 4);
quadraticBoundingBox = computeQuadraticBoundingBox.apply(this, lastPoint.concat(segment));
xs.push(quadraticBoundingBox.minx);
xs.push(quadraticBoundingBox.maxx);
ys.push(quadraticBoundingBox.miny);
ys.push(quadraticBoundingBox.maxy);
// reflected control point for the next possible T
quadraticСontrolPoint = [
2 * segment[2] - segment[0],
2 * segment[3] - segment[1]
];
lastPoint = segment.slice(-2);
}
// S
} else if (pathItem.instruction === 'T') {
for (i = 0; i < pathItem.data.length; i += 2) {
segment = pathItem.data.slice(i, i + 2);
quadraticBoundingBox = computeQuadraticBoundingBox.apply(this, lastPoint.concat(quadraticСontrolPoint).concat(segment));
xs.push(quadraticBoundingBox.minx);
xs.push(quadraticBoundingBox.maxx);
ys.push(quadraticBoundingBox.miny);
ys.push(quadraticBoundingBox.maxy);
// reflected control point for the next possible T
quadraticСontrolPoint = [
2 * segment[0] - quadraticСontrolPoint[0],
2 * segment[1] - quadraticСontrolPoint[1]
];
lastPoint = segment.slice(-2);
}
}
});
var xmin = Math.min.apply(this, xs).toFixed(params.floatPrecision),
xmax = Math.max.apply(this, xs).toFixed(params.floatPrecision),
ymin = Math.min.apply(this, ys).toFixed(params.floatPrecision),
ymax = Math.max.apply(this, ys).toFixed(params.floatPrecision),
svgWidth = +svgElem.attr('width').value,
svgHeight = +svgElem.attr('height').value,
realWidth = Math.round(xmax - xmin),
realHeight = Math.round(ymax - ymin),
transform = '',
scale;
// width & height
if (params.width && params.height) {
scale = Math.min(params.width / svgWidth, params.height / svgHeight);
realWidth = realWidth * scale;
realHeight = realHeight * scale;
svgWidth = svgElem.attr('width').value = params.width;
svgHeight = svgElem.attr('height').value = params.height;
transform += ' scale(' + scale + ')';
// width
} else if (params.width && !params.height) {
scale = params.width / svgWidth;
realWidth = realWidth * scale;
realHeight = realHeight * scale;
svgWidth = svgElem.attr('width').value = params.width;
svgHeight = svgElem.attr('height').value = svgHeight * scale;
transform += ' scale(' + scale + ')';
// height
} else if (params.height && !params.width) {
scale = params.height / svgHeight;
realWidth = realWidth * scale;
realHeight = realHeight * scale;
svgWidth = svgElem.attr('width').value = svgWidth * scale;
svgHeight = svgElem.attr('height').value = params.height;
transform += ' scale(' + scale + ')';
}
// shiftX
if (params.shiftX) {
transform += ' translate(' + realWidth * params.shiftX + ', 0)';
}
// shiftY
if (params.shiftY) {
transform += ' translate(0, ' + realHeight * params.shiftY + ')';
}
// scale
if (params.scale) {
scale = params.scale;
var shiftX = svgWidth / 2,
shiftY = svgHeight / 2;
realWidth = realWidth * scale;
realHeight = realHeight * scale;
if (params.shiftX || params.shiftY) {
transform += ' scale(' + scale + ')';
} else {
transform += ' translate(' + shiftX + ' ' + shiftY + ') scale(' + scale + ') translate(-' + shiftX + ' -' + shiftY + ')';
}
}
// hcrop
if (params.hcrop) {
transform += ' translate(' + (-xmin) + ' 0)';
svgElem.attr('width').value = realWidth;
}
// vcenter
if (params.vcenter) {
transform += ' translate(0 ' + (((svgHeight - realHeight) / 2) - ymin) + ')';
}
if (transform) {
pathElem.addAttr({
name: 'transform',
prefix: '',
local: 'transform',
value: transform
});
path = applyTransforms(pathElem, pathElem.pathJS, true, params.floatPrecision);
// transformed data rounding
path.forEach(function(pathItem) {
if (pathItem.data) {
pathItem.data = pathItem.data.map(function(num) {
return +num.toFixed(params.floatPrecision);
});
}
});
// save new
js2path(pathElem, path, params);
}
}
});
return data;
};