Skip to content

Commit

Permalink
Merge bb85cfd into 102a721
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshyPHP committed Jun 9, 2018
2 parents 102a721 + bb85cfd commit 4a60e51
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 0 deletions.
1 change: 1 addition & 0 deletions .svgo.yml
Expand Up @@ -41,6 +41,7 @@ plugins:
- removeHiddenElems
- removeEmptyText
- convertShapeToPath
- removeOffCanvasPaths
- moveElemsAttrsToGroup
- moveGroupAttrsToElems
- collapseGroups
Expand Down
76 changes: 76 additions & 0 deletions plugins/removeOffCanvasPaths.js
@@ -0,0 +1,76 @@
'use strict';

exports.type = 'perItem';

exports.active = false;

exports.description = 'removes elements that are drawn outside of the viewbox (disabled by default)';

var SVGO = require('../lib/svgo.js'),
_path = require('./_path.js'),
intersects = _path.intersects,
path2js = _path.path2js,
viewBoxJS;

/**
* Remove elements that are drawn outside of the viewbox.
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author JoshyPHP
*/
exports.fn = function(item) {

if (item.isElem('path') && typeof viewBoxJS !== 'undefined')
{
return intersects(viewBoxJS, path2js(item));
}
if (item.isElem('svg'))
{
viewBoxJS = getViewBoxJS(item);
}

return true;
};

/**
* Compute the JS representation of the viewbox's path.
*
* @param {Object} svg svg element item
* @return {Object} JS representation, or undefined
*/
function getViewBoxJS(svg)
{
var viewbox = '';
if (svg.hasAttr('viewBox'))
{
// Remove commas and plus signs, normalize and trim whitespace
viewbox = svg.attr('viewBox').value.replace(/[,+]|px/g, ' ').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
}
else if (svg.hasAttr('height') && svg.hasAttr('width'))
{
viewbox = '0 0 ' + svg.attr('width').value + ' ' + svg.attr('height').value;
}

// Test that the dimensions are 4 values separated by space
var m = /^(-?\d*\.?\d+) (-?\d*\.?\d+) (\d*\.?\d+) (\d*\.?\d+)$/.exec(viewbox);
if (!m)
{
return undefined;
}

var path = new SVGO().createContentItem({
elem: 'path',
prefix: '',
local: 'path'
});
path.addAttr({
name: 'd',
prefix: '',
local: 'd',
value: 'M' + m[1] + ' ' + m[2] + 'h' + m[3] + 'v' + m[4] + 'H' + m[1] + 'z'
});

return path2js(path);
}
13 changes: 13 additions & 0 deletions test/plugins/removeOffCanvasPaths.01.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions test/plugins/removeOffCanvasPaths.02.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 4a60e51

Please sign in to comment.