schnee effeckt und fehler Korektur
This commit is contained in:
11
node_modules/svgo/.npmignore
generated
vendored
11
node_modules/svgo/.npmignore
generated
vendored
@@ -1,11 +0,0 @@
|
||||
docs
|
||||
examples
|
||||
test
|
||||
lib-cov
|
||||
.editorconfig
|
||||
.jshintignore
|
||||
.jshintrc
|
||||
.travis.yml
|
||||
lcov.info
|
||||
logo.svg
|
||||
CHANGELOG.MD
|
||||
65
node_modules/svgo/.svgo.yml
generated
vendored
65
node_modules/svgo/.svgo.yml
generated
vendored
@@ -1,65 +0,0 @@
|
||||
# replace default config
|
||||
|
||||
# multipass: true
|
||||
# full: true
|
||||
|
||||
plugins:
|
||||
|
||||
# - name
|
||||
#
|
||||
# or:
|
||||
# - name: false
|
||||
# - name: true
|
||||
#
|
||||
# or:
|
||||
# - name:
|
||||
# param1: 1
|
||||
# param2: 2
|
||||
|
||||
- removeDoctype
|
||||
- removeXMLProcInst
|
||||
- removeComments
|
||||
- removeMetadata
|
||||
- removeEditorsNSData
|
||||
- cleanupAttrs
|
||||
- minifyStyles
|
||||
- convertStyleToAttrs
|
||||
- cleanupIDs
|
||||
- removeRasterImages
|
||||
- removeUselessDefs
|
||||
- cleanupNumericValues
|
||||
- cleanupListOfValues
|
||||
- convertColors
|
||||
- removeUnknownsAndDefaults
|
||||
- removeNonInheritableGroupAttrs
|
||||
- removeUselessStrokeAndFill
|
||||
- removeViewBox
|
||||
- cleanupEnableBackground
|
||||
- removeHiddenElems
|
||||
- removeEmptyText
|
||||
- convertShapeToPath
|
||||
- moveElemsAttrsToGroup
|
||||
- moveGroupAttrsToElems
|
||||
- collapseGroups
|
||||
- convertPathData
|
||||
- convertTransform
|
||||
- removeEmptyAttrs
|
||||
- removeEmptyContainers
|
||||
- mergePaths
|
||||
- removeUnusedNS
|
||||
- transformsWithOnePath
|
||||
- sortAttrs
|
||||
- removeTitle
|
||||
- removeDesc
|
||||
- removeDimensions
|
||||
- removeAttrs
|
||||
- addClassesToSVGElement
|
||||
- removeStyleElement
|
||||
|
||||
# configure the indent (default 4 spaces) used by `--pretty` here:
|
||||
#
|
||||
# @see https://github.com/svg/svgo/blob/master/lib/svgo/js2svg.js#L6 for more config options
|
||||
#
|
||||
# js2svg:
|
||||
# pretty: true
|
||||
# indent: ' '
|
||||
398
node_modules/svgo/CHANGELOG.md
generated
vendored
398
node_modules/svgo/CHANGELOG.md
generated
vendored
@@ -1,398 +0,0 @@
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.6) ] 0.6.6 / 25.04.2016
|
||||
* Corrected CSSO API usage
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.5) ] 0.6.5 / 25.04.2016
|
||||
* Extra content inserted by editors are now being removed within `<foreignObject>` as well thus fixing bug “Namespace prefix … is not defined“ after applying SVGO.
|
||||
* Doctype with entities declartion is now also being removed since svgo correctly parses them starting from the version [0.6.2](https://github.com/svg/svgo/tree/v0.6.2).
|
||||
* Corrected `moveGroupAttrsToElems` not to move attributes to `g` content if it's referenced (has an `id`).
|
||||
* `collapseGroups` now don't collapse a group if it has an animated attribute (SMIL).
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.4) ] 0.6.4 / 05.04.2016
|
||||
* Fixed bug in “[convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js)” plugin with converting styling properties to non-existent attributes (which are normally removed later by `removeUnknownsAndDefaults`).
|
||||
* Added `--indent` option to style pretty-printed SVG. (e.g. `--indent 2`) (by @scurker).
|
||||
* Added `currentColor` param to `convertColors` plugin for converting values like `fill` and `stroke` to `currentColor` (by @scurker).
|
||||
* Bumped CSSO to the current version and used [its new shiny API](https://github.com/css/csso#api) (thanks to @lahmatiy).
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.3) ] 0.6.3 / 20.03.2016
|
||||
* Smart rounding (introduced in 0.4.5) now applies only when rounding is needed, thus making subsequent passes more stable.
|
||||
* Fixed regression in converting curves to arcs.
|
||||
* `xlink:href` references are now being checked by local name `href`, thus correctly working with another namespace prefix.
|
||||
* Fixed `id` removing with disabled `plugins/convertStyleToAttrs.js`.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.2) ] 0.6.2 / 08.03.2016
|
||||
* Better error handling and messaging improvements.
|
||||
* SVG files with XML entities (e.g. from Adobe Illustrator) are now correctly being parsed.
|
||||
* Fixed error on converting curves to arcs.
|
||||
* Corrected rounding in subsequent passes with `--multipass` option.
|
||||
* Data URI option now handles charset (by @holymonson)
|
||||
* Tranformations are no longer moved to group if there is a mask (`plugins/moveElemsAttrsToGroup.js`).
|
||||
* Fixed matrix decomposition losing sign in case like `[1, 0, 0, -1, 0, 0]` (`scale(1 -1)`).
|
||||
* Fixed crash on uppercased color name.
|
||||
* Paths with `id` and without `stroke-width` aren't being trasformed now since `stroke-width` may be applied later.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.1) ] 0.6.1 / 21.11.2015
|
||||
* Added option `--quiet` to suppress output (by @phihag).
|
||||
* Removed `lib-cov` folder from the package, which was erroneously included before.
|
||||
* Fixed errors in “[minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js)” when there are `<style>` elements with `CDATA` content or without content at all.
|
||||
* Amended transform functions parsing to prevent errors when there are no separators between numbers (which isn't allowed by syntax, but understood by browsers).
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.6.0) ] 0.6.0 / 08.11.2015
|
||||
* New optimization: circular curves now being converted to arcs. A notable improvement for circles within paths.
|
||||
* New plugin “[minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js)” which minifies `<style>` elments content with CSSO by @strarsis (svgo still doesn't understand its content)
|
||||
* New plugin “[removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js)” (disabled by default) by @betsydupuis.
|
||||
* Fixed issues wuth parsing numbers with exponent fraction (could happen with high precision >= 7).
|
||||
* Fixed rounding error due to incorrect preserving of precision in transformations.
|
||||
* Fixed shortand curve distortion due to converted previous curve to not a curve.
|
||||
* Fixed interoperability issue with `precision` cli-option and `full` config.
|
||||
* Fixed an error produced by “[removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js)” by @thiakil
|
||||
* Another Inkscape prefix namespace is being removed.
|
||||
* Fixed an issue in [moveElemsAttrsToGroup“](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup“.js)” with transforms moved around `clip-path`.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.6) ] 0.5.6 / 13.08.2015
|
||||
* Fixed paths removing.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.5) ] 0.5.5 / 05.08.2015
|
||||
* Reverted debugging changes.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.4) ] 0.5.4 / 05.08.2015
|
||||
* New parameter `useShortTags` by @bradbarrow. Now svgo can produce correct non-selfclosing tags (useful in HTML in old browsers).
|
||||
* Fixed failing on empty transformation (which could be produced by two opposite).
|
||||
* Fixed removing paths which have numbers with exponent notation.
|
||||
* Fixed a bug with arc transformation.
|
||||
* Some typo fixes.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.3) ] 0.5.3 / 21.06.2015
|
||||
* Fixed breaking related to rounding functions in “[convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js)”.
|
||||
* Fixed a bug with ID in animations not being worked on by “[cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js)”.
|
||||
* Fixed a bug with quoted reference in `url()`.
|
||||
* Now, if there are several same IDs in the document, then the first one is used and others are being removed.
|
||||
* New command-line option `--show-plugins` displaying list of plugins.
|
||||
* Two new optional plugins: “[removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js)” (removes `width` and `height` if there is `viewBox`) and “[removeAttrsPlugin](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js)” (by @bennyschudel).
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.2) ] 0.5.2 / 24.05.2015
|
||||
* Introduced new `transformPrecision` option for better image quality (defaults to 5) in “[convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js)” and “[convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js)” (for the purpose of applying transformations) plugins.
|
||||
* Matrix transformations now can be decomposed into a combination of few simple transforms like `translate`, `rotate`, `scale`.
|
||||
* Arcs (paths `arcto` command) are now correctly being transformed into another arcs without being converting to Bezier curves.
|
||||
* Fixed an issue with “[mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js)” failing to detect paths intersection in some cases.
|
||||
* Fixed a bug with “[removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js)” removing some paths, which was introduced in [v0.5.1](https://github.com/svg/svgo/tree/v0.5.1).
|
||||
* Fixed a bug with transformation having `rotate()` with optional parameters.
|
||||
* Patterns with inherited attributes are no longer being removed.
|
||||
* Styles are no longer being removed from `<desc>` (by @dennari).
|
||||
* SVGO no longer breaks during parsing.
|
||||
* Added `clone()` method to JSAPI (by @jakearchibald)
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.1) ] 0.5.1 / 30.03.2015
|
||||
* added new command-line option to set precision in floating point numbers.
|
||||
* fixed all known image-disruptive bugs
|
||||
* Notably [mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) plugin now checks for possible intersections to avoid side-effects
|
||||
* new plugin [removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) to remove elements in ``<defs>`` and similar non-rendering elements without an ``id`` and thus cannot be used
|
||||
* fix for ``--multipass`` command line option (by @dfilatov)
|
||||
* improved [cleanupEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) and [convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) plugins (by @YetiOr)
|
||||
* new plugin for image manipulation [cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) (by @kiyopikko)
|
||||
* fixed fail on comments after closing root ``</svg>`` tag
|
||||
* updated parsing to account meaningful spaces in ``<text>``
|
||||
* ``data-*`` attributes are now preserved in [removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js)
|
||||
* prevented plugins from failing in ``<foreignObject>``
|
||||
* [cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) plugin now converts other units to pixels (if it's better)
|
||||
* [removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) plugin is enabled again with correct work in case of inherited attributes
|
||||
* fixed fail on images with incorrect paths like ``<path d="z"/>``
|
||||
* svgo now understands if an input is a folder (remember, you can set output to folder as well)
|
||||
* added support for some properties from SVG 2 like ``vector-effect="non-scaling-stroke"``
|
||||
* removed option to remove an ``id`` on root ``<svg>`` tag in [removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) since it's already being done in [cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js)
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.5.0) ] 0.5.0 / 05.11.2014
|
||||
* added ``--multipass`` command line option which repeatedly applies optimizations like collapsing groups (by @dfilatov)
|
||||
* exposed JSAPI as a factory method (by @mistakster)
|
||||
* added removeDesc plugin (by @dwabyick), disabled by default
|
||||
* [removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) plugin is disabled by default since it's unable to check inherited properties
|
||||
* transformations now apply to paths with arcs in [plugins/convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js)
|
||||
* a lot of bug fixes mostly related to transformations
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.5) ] 0.4.5 / 02.08.2014
|
||||
* significally improved plugin [plugins/convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js):
|
||||
- Now data is being written relative or absolute whichever is shorter. You can turn it off by setting ``utilizeAbsolute`` to ``false``.
|
||||
- Smarter rounding: values like 2.499 now rounds to 2.5. Rounding now takes in account accumulutive error meaning that points will not be misplaced due to rounding more than it neccessary.
|
||||
- Fixed couple bugs.
|
||||
* ``--output`` option now can be a folder along with ``--folder``, thanks to @mako-taco.
|
||||
* [plugins/cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) now have ``prefix`` option in case you want to combine multiple svg later (by @DanielMazurkiewicz).
|
||||
* Quotes now being escaped in attributes (by @ditesh).
|
||||
* Minor bugfixes.
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.4) ] 0.4.4 / 14.01.2014
|
||||
* new plugin [plugins/removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) (disabled by default, close [#159](https://github.com/svg/svgo/issues/159))
|
||||
* plugins/convertPathData: skip data concatenation for z instruction in collapseRepeated
|
||||
* plugins/removeUnknownsAndDefaults: do not remove overriden attributes with default values (fix [#161](https://github.com/svg/svgo/issues/161) and [#168](https://github.com/svg/svgo/issues/168))
|
||||
* plugins/removeViewBox: disable by default (fix [#139](https://github.com/svg/svgo/issues/139))
|
||||
* update README with [gulp task](https://github.com/ben-eb/gulp-svgmin)
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.3) ] 0.4.3 / 02.01.2014
|
||||
* new plugin [plugins/convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) (close [#96](https://github.com/svg/svgo/issues/96))
|
||||
* update sax version to fix [#140](https://github.com/svg/svgo/issues/140)
|
||||
* update deps
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.2) ] 0.4.2 / 19.12.2013
|
||||
* add `lcov.info` to npmignore
|
||||
* fix `js-yaml` version to suppress deprecation warning in stdout
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.1) ] 0.4.1 / 18.11.2013
|
||||
* node >=0.8.0
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.4.0) ] 0.4.0 / 18.11.2013
|
||||
* merge almost all pull-requests
|
||||
* update dependencies
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.7) ] 0.3.7 / 24.06.2013
|
||||
* do not remove `result` attribute from filter primitives (fix [#122](https://github.com/svg/svgo/issues/122))
|
||||
* plugins/cleanupAttrs: replace newline with space when needed (fix [#119](https://github.com/svg/svgo/issues/119))
|
||||
* lib/coa: look for config file in current folder
|
||||
* lib/coa: always traverse all files in the given folder
|
||||
* deprecate svgo-grunt in favor of [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin)
|
||||
* re-enable node-coveralls
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.6) ] 0.3.6 / 06.06.2013
|
||||
* plugins/removeNonInheritableGroupAttrs: more attrs groups to exclude (fix [#116](https://github.com/svg/svgo/issues/116) & [#118](https://github.com/svg/svgo/issues/118))
|
||||
* lib/coa: optimize folder file by file (temp fix [#114](https://github.com/svg/svgo/issues/114))
|
||||
* `.jshintrc`: JSHint 2.0
|
||||
* temporarily disable node-coveralls
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.5) ] 0.3.5 / 07.05.2013
|
||||
* plugins/transformsWithOnePath: fix curves bounding box calculation
|
||||
* plugins/transformsWithOnePath: fix possible c+t or q+s bug
|
||||
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.4) ] 0.3.4 / 06.05.2013
|
||||
* plugins/convertPathData: fix m->M bug in some cases
|
||||
* plugins/transformsWithOnePath: fix last point calculation for C/S/Q/T
|
||||
* plugins/mergePaths: add space delimiter between z and m
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.3) ] 0.3.3 / 05.05.2013
|
||||
* plugins/convertPathData: convert very first m to M, fix applyTransforms with translate() (fix [#112](https://github.com/svg/svgo/issues/112))
|
||||
* plugins/transformsWithOnePath: fix real width/height rounding; fix scale transform origin; reorder transforms
|
||||
* plugins/transformsWithOnePath: ability to set new width or height independently with auto rescaling
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.2) ] 0.3.2 / 03.05.2013
|
||||
* new plugin [plugins/sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js)
|
||||
* plugins/transformsWithOnePath: buggy hcrop (fix [#111](https://github.com/svg/svgo/issues/111))
|
||||
* Impossible to set output presision to 0 (no fractional part) (fix [#110](https://github.com/svg/svgo/issues/110))
|
||||
* Istanbul + coveralls.io
|
||||
* update README with NPM version from badge.fury.io
|
||||
* update README with dependency status from gemnasium.com
|
||||
* npmignore unneeded files
|
||||
* reoptimized project logo
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.1) ] 0.3.1 / 15.04.2013
|
||||
* plugins/transformsWithOnePath: resize SVG and automatically rescale inner Path
|
||||
* better errors handling
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.3.0) ] 0.3.0 / 12.04.2013
|
||||
* global refactoring: getting rid of the many dependencies
|
||||
* new plugin [plugins/mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js)
|
||||
* new plugin [plugins/transformsWithOnePath](https://github.com/svg/svgo/blob/master/plugins/transformsWithOnePath.js) (renamed and featured `cropAndCenterAlongPath`)
|
||||
* config: replace default config with `full: true`
|
||||
* coa: JSON string as value of `--config`
|
||||
* coa: different types of Data URI strings (close [#105](https://github.com/svg/svgo/issues/105))
|
||||
* plugins/_transforms: allow spaces at the beginning of transform
|
||||
* Travis CI: Nodejs 0.10 & 0.11
|
||||
* `node.extend` → `whet.extend`
|
||||
* update `.gitignore`
|
||||
* update docs
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.2.4) ] 0.2.4 / 05.04.2013
|
||||
* new plugin [plugins/cropAndCenterAlongPath](https://github.com/svg/svgo/blob/master/plugins/cropAndCenterAlongPath.js) for the [Fontello](https://github.com/fontello) project
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.2.3) ] 0.2.3 / 22.02.2013
|
||||
* new plugin [plugins/removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) (fix [#101](https://github.com/svg/svgo/issues/101))
|
||||
* new plugin [plugins/removeRasterImages](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) (close [#98](https://github.com/svg/svgo/issues/98))
|
||||
* plugins/convertTransform: bug with trailing spaces in transform value string (fix [#103](https://github.com/svg/svgo/issues/103))
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.2.2) ] 0.2.2 / 09.02.2013
|
||||
* plugins/convertTransforms: wrong translate() shorthand (fix [#94](https://github.com/svg/svgo/issues/94))
|
||||
* [yaml.js](https://github.com/jeremyfa/yaml.js) → [js-yaml](https://github.com/nodeca/js-yaml)
|
||||
* update outdated deps
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.2.1) ] 0.2.1 / 18.01.2013
|
||||
* plugins/moveElemsAttrsToGroup + plugins/moveGroupAttrsToElems: move or just leave transform attr from Group to the inner Path Elems (close [#86](https://github.com/svg/svgo/issues/86))
|
||||
* plugins/removeViewBox: doesn't catch floating-point numbers (fix [#88](https://github.com/svg/svgo/issues/88))
|
||||
* plugins/cleanupEnableBackground: doesn't catch floating-point numbers (fix [#89](https://github.com/svg/svgo/issues/89))
|
||||
* plugins/cleanupNumericValues: wrong floating-point numbers regexp (fix [#92](https://github.com/svg/svgo/issues/92))
|
||||
* SVG file generated by fontcustom.com not properly compressed (fix [#90](https://github.com/svg/svgo/issues/90))
|
||||
* `README.ru.md`: стилизация русского языка, улучшение языковых конструкций, правка ошибок (close [#91](https://github.com/svg/svgo/issues/91))
|
||||
* minor JSHint warning fix
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.2.0) ] 0.2.0 / 23.12.2012
|
||||
* plugins/convertPathData: apply transforms to Path pata (close [#33](https://github.com/svg/svgo/issues/33))
|
||||
* plugins/convertPathData: `-1.816-9.278.682-13.604` parsing error (fix [#85](https://github.com/svg/svgo/issues/85))
|
||||
* plugins/convertTransform: `translate(10, 0)` eq `translate(10)`, but not `translate(10, 10)` eq `translate(10)` (fix [#83](https://github.com/svg/svgo/issues/83))
|
||||
* run plugins/cleanupIDs before plugins/collapseGroups (fix [#84](https://github.com/svg/svgo/issues/84))
|
||||
* update `.gitignore`
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.9) ] 0.1.9 / 17.12.2012
|
||||
* plugins/cleanupIDs: renamed from removeUnusedIDs; minify used IDs (fix [#7](https://github.com/svg/svgo/issues/7))
|
||||
* lib/svgo/js2svg: restore HTML entities back (fix [#80](https://github.com/svg/svgo/issues/80) + [#81](https://github.com/svg/svgo/issues/81))
|
||||
* plugins/removeDoctype: do not remove if custom XML entities presents (fix [#77](https://github.com/svg/svgo/issues/77))
|
||||
* lib/svgo/coa: refactoring, colors and fix [#70](https://github.com/svg/svgo/issues/70)
|
||||
* lib/svgo: store elapsed time in result object
|
||||
* usage examples with SVGZ (close [#18](https://github.com/svg/svgo/issues/18))
|
||||
* more optimized logo
|
||||
* update `.gitignore`
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.8) ] 0.1.8 / 11.12.2012
|
||||
* new plugin [plugins/removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) (close [#75](https://github.com/svg/svgo/issues/75))
|
||||
* new plugin [plugins/removeUnusedIDs](https://github.com/svg/svgo/blob/master/plugins/removeUnusedIDs.js) (close [#76](https://github.com/svg/svgo/issues/76))
|
||||
* plugins/convertPathData: wrong M interpretation in some cases (fix [#73](https://github.com/svg/svgo/issues/73))
|
||||
* plugins/cleanupAttrs: use `isElem()` API
|
||||
* `.travis.yml`: check all branches
|
||||
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.7) ] 0.1.7 / 08.12.2012
|
||||
* plugins/convertPathData: incorrect interpretation of `z + m` (fix [#69](https://github.com/svg/svgo/issues/69))
|
||||
* plugins/convertTransform: do a more accurate floating numbers rounding in `matrixToTransform()` (fix [#68](https://github.com/svg/svgo/issues/68))
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.6) ] 0.1.6 / 07.12.2012
|
||||
* plugins/convertPathData: collapse repeated instructions only after curveSmoothShorthands (fix [#64](https://github.com/svg/svgo/issues/64))
|
||||
* lib/svgo/coa: handle 'there is nothing to optimize' case and display a message about it (fix [#61](https://github.com/svg/svgo/issues/61))
|
||||
* plugins/cleanupSVGElem: delete as useless artefact
|
||||
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.5) ] 0.1.5 / 06.12.2012
|
||||
* E-notated numbers in paths not recognised (fix [#63](https://github.com/svg/svgo/issues/63))
|
||||
* update README with `svgo-grunt` and `svgo-osx-folder-action`
|
||||
* fix `mocha-as-promised` plug in node 0.6
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.4) ] 0.1.4 / 05.12.2012
|
||||
* plugins/_collections: more defaults
|
||||
* `README.ru.md`
|
||||
* `docs/how-it-works/ru.md`
|
||||
* mocha + mocha-as-promised + chai + chai-as-promised + should + istanbul = <3
|
||||
* update dependencies semvers in `package.json`
|
||||
* `v0.1.x` and `v0.2.x` milestones
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.3) ] 0.1.3 / 30.11.2012
|
||||
* new plugin [plugins/cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) (close [#8](https://github.com/svg/svgo/issues/8))
|
||||
* plugins/removeDefaultPx functionality now included in plugins/removeUnknownsAndDefaults
|
||||
* plugins/removeUnknownsAndDefaults: refactoring and picking up the complete elems+attrs collection (close [#59](https://github.com/svg/svgo/issues/59))
|
||||
* plugins/convertTransform: error in matrices multiplication (fix [#58](https://github.com/svg/svgo/issues/58))
|
||||
* plugins/convertTransform: mark translate() and scale() as useless only with one param (fix [#57](https://github.com/svg/svgo/issues/57))
|
||||
* plugins/convertPathData: drastic speed improvement with huge Path data
|
||||
* plugins/convertPathData: fix the very first Mm with multiple points (fix [#56](https://github.com/svg/svgo/issues/56))
|
||||
* plugins/moveElemsAttrsToGroup: additional check for transform attr
|
||||
* brand-new project `logo.svg`
|
||||
* `.travis.yml`: build only master branch
|
||||
* global `'use strict'`
|
||||
* `.jshintignore`
|
||||
* README and CHANGELOG: minor corrections
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.2) ] 0.1.2 / 24.11.2012
|
||||
* lib/svgo/svg2js: correct 'onerror' failure (fix [#51](https://github.com/svg/svgo/issues/51))
|
||||
* config: disable sax-js position tracking by default (fix [#52](https://github.com/svg/svgo/issues/52))
|
||||
* lib/svgo: rename 'startBytes' to 'inBytes' and 'endBytes' to 'outBytes' (close [#53](https://github.com/svg/svgo/issues/53))
|
||||
* plugins/removeUnknownsAndDefaults: remove SVG id attr (close [#54](https://github.com/svg/svgo/issues/54))
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.1) ] 0.1.1 / 23.11.2012
|
||||
* plugins/moveElemsAttrsToGroup: fix inheitable only attrs array (fix [#47](https://github.com/svg/svgo/issues/47))
|
||||
* plugins/removeEmptyContainers: do not remove an empty 'svg' element (fix [#48](https://github.com/svg/svgo/issues/48))
|
||||
* plugins/removeDefaultPx: should also understand a floating-numbers too (fix [#49](https://github.com/svg/svgo/issues/49))
|
||||
* plugins/removeUnknownsAndDefaults: merge multiple groupDefaults attrs (close [#50](https://github.com/svg/svgo/issues/50))
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.1.0) ] 0.1.0 / 22.11.2012
|
||||
* new plugin [plugins/removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) (close [#6](https://github.com/svg/svgo/issues/6))
|
||||
* plugins/convertPathData: convert straight curves into lines segments (close [#17](https://github.com/svg/svgo/issues/17)); remove an absolute coords conversions
|
||||
* plugins/convertPathData: convert quadratic Bézier curveto into smooth shorthand (close [#31](https://github.com/svg/svgo/issues/31))
|
||||
* plugins/convertPathData: convert curveto into smooth shorthand (close [#30](https://github.com/svg/svgo/issues/30))
|
||||
* lib/svgo: global API refactoring (close [#37](https://github.com/svg/svgo/issues/37))
|
||||
* lib/svgo: fatal and stupid error in stream chunks concatenation (fix [#40](https://github.com/svg/svgo/issues/40))
|
||||
* lib/coa: batch folder optimization (close [#29](https://github.com/svg/svgo/issues/29))
|
||||
* lib/coa: support arguments as aliases to `--input` and `--output` (close [#28](https://github.com/svg/svgo/issues/28))
|
||||
* project logo by [Egor Bolhshakov](http://xizzzy.ru/)
|
||||
* move modules to `./lib/svgo/`
|
||||
* rename and convert `config.json` to `.svgo.yml`
|
||||
* add [./docs/](https://github.com/svg/svgo/tree/master/docs)
|
||||
* plugins/convertPathData: don't remove first `M` even if it's `0,0`
|
||||
* plugins/convertPathData: stronger defense from infinite loop
|
||||
* plugins/moveElemsAttrsToGroup: should affect only inheritable attributes (fix [#46](https://github.com/svg/svgo/issues/46))*
|
||||
* plugins/removeComments: ignore comments which starts with '!' (close [#43](https://github.com/svg/svgo/issues/43))
|
||||
* config: `cleanupAttrs` should be before `convertStyleToAttrs` (fix [#44](https://github.com/svg/svgo/issues/44))*
|
||||
* lib/svgo/jsAPI: add `eachAttr()` optional context param
|
||||
* temporarily remove PhantomJS and `--test` (close [#38](https://github.com/svg/svgo/issues/38))
|
||||
* q@0.8.10 compatibility: 'end is deprecated, use done instead' fix
|
||||
* add [Istanbul](https://github.com/gotwarlost/istanbul) code coverage
|
||||
* update dependencies versions and gitignore
|
||||
* README: add TODO section with versions milestones
|
||||
* update README with License section
|
||||
* update LICENSE with russian translation
|
||||
* `.editorconfig`: 2 spaces for YAML
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.9) ] 0.0.9 / 29.10.2012
|
||||
* [plugins how-to](https://github.com/svg/svgo/tree/master/plugins#readme) (close [#27](https://github.com/svg/svgo/issues/27))
|
||||
* allow any plugin of any type to go in any order (close [#14](https://github.com/svg/svgo/issues/14))
|
||||
* allow to do a multiple optimizations with one init (close [#25](https://github.com/svg/svgo/issues/25))
|
||||
* plugins/convertPathData: global refactoring
|
||||
* plugins/convertPathData: do all the tricks with absolute coords too (fix [#22](https://github.com/svg/svgo/issues/22))
|
||||
* plugins/convertPathData: accumulation of rounding errors (fix [#23](https://github.com/svg/svgo/issues/23))
|
||||
* plugins/convertPathData: prevent an infinity loop on invalid path data (fix [#26](https://github.com/svg/svgo/issues/26))
|
||||
* plugins/convertPathData: do not remove very first M from the path data (fix [#24](https://github.com/svg/svgo/issues/24))
|
||||
* plugins/convertPathData: optimize path data in <glyph> and <missing-glyph> (close [#20](https://github.com/svg/svgo/issues/20))
|
||||
* plugins/convertTransform: add patternTransform attribute to the process (close [#15](https://github.com/svg/svgo/issues/15))
|
||||
* plugins/convertTransform: Firefox: removing extra space in front of negative number is alowed only in path data, but not in transform (fix [#12](https://github.com/svg/svgo/issues/12))
|
||||
* plugins/removeXMLProcInst: remove only 'xml' but not 'xml-stylesheet' (fix [#21](https://github.com/svg/svgo/issues/15))
|
||||
* plugins/collapseGroups: merge split-level transforms (fix [#13](https://github.com/svg/svgo/issues/13))
|
||||
* jsdoc corrections
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.8) ] 0.0.8 / 20.10.2012
|
||||
* new plugin [convertTransform](plugins/convertTransform.js) (close [#5](https://github.com/svg/svgo/issues/5))
|
||||
* new plugin [removeUnusedNS](plugins/removeUnusedNS.js)
|
||||
* plugins/convertPathData: remove useless segments
|
||||
* plugins/convertPathData: a lot of refactoring
|
||||
* plugins/convertPathData: round numbers before conditions because of exponential notation (fix [#3](https://github.com/svg/svgo/issues/3))
|
||||
* plugins/moveElemsAttrsToGroup: merge split-level transforms instead of replacing (fix [#10](https://github.com/svg/svgo/issues/10))
|
||||
* lib/svg2js: catch and output xml parser errors (fix [#4](https://github.com/svg/svgo/issues/4))
|
||||
* lib/coa: open file for writing only when we are ready (fix [#2](https://github.com/svg/svgo/issues/2))
|
||||
* lib/tools: node.extend module
|
||||
* lib/plugins: refactoring
|
||||
* lib/js2svg: refactoring
|
||||
* lib/jsAPI: simplification and refactoring
|
||||
* absolute urls in README
|
||||
* update .editorconfig
|
||||
* update .travis.yml with nodejs 0.9
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.7) ] 0.0.7 / 14.10.2012
|
||||
* new plugin [convertPathData](plugins/convertPathData.js)
|
||||
* --input data now can be a Data URI base64 string
|
||||
* --output data now can be a Data URI base64 string with --datauri flag
|
||||
* Travis CI
|
||||
* JSHint corrections + .jshintrc
|
||||
* [.editorconfig](http://editorconfig.org/)
|
||||
* display time spent on optimization
|
||||
* .svgo → config.json
|
||||
* lib/phantom_wrapper.js → lib/phantom.js
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.6) ] 0.0.6 / 04.10.2012
|
||||
* add --test option to make a visual comparison of two files (PhantomJS pre-required)
|
||||
* update README and CHANGELOG with the correct relative urls
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.5) ] 0.0.5 / 03.10.2012
|
||||
* every plugin now has [at least one test](plugins)
|
||||
* removeViewBox, cleanupEnableBackground, removeEditorsNSData, convertStyleToAttrs and collapseGroups plugins fixes
|
||||
* new --pretty option for the pretty printed SVG
|
||||
* lib/config refactoring
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.4) ] 0.0.4 / 30.09.2012
|
||||
* new plugin [removeViewBox](plugins/removeViewBox.js)
|
||||
* new plugin [cleanupEnableBackground](plugins/cleanupEnableBackground.js)
|
||||
* display useful info after successful optimization
|
||||
* 'npm test' with 'spec' mocha output by default
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.3) ] 0.0.3 / 29.09.2012
|
||||
* plugins/collapseGroups bugfix
|
||||
* plugins/moveElemsAttrsToGroup bugfix
|
||||
* svgo now display --help if running w/o arguments
|
||||
* massive jsdoc updates
|
||||
* plugins engine main filter function optimization
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.2) ] 0.0.2 / 28.09.2012
|
||||
* add --disable and --enable command line options
|
||||
* add an empty values rejecting to coa.js
|
||||
* update README
|
||||
|
||||
### [ [>](https://github.com/svg/svgo/tree/v0.0.1) ] 0.0.1 / 27.09.2012
|
||||
* initial public version
|
||||
68
node_modules/svgo/LICENSE
generated
vendored
68
node_modules/svgo/LICENSE
generated
vendored
@@ -1,55 +1,21 @@
|
||||
The MIT License
|
||||
MIT License
|
||||
|
||||
Copyright © 2012–2016 Kir Belevich
|
||||
Copyright (c) Kir Belevich
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
Лицензия MIT
|
||||
|
||||
Copyright © 2012–2016 Кир Белевич
|
||||
|
||||
Данная лицензия разрешает лицам, получившим копию данного
|
||||
программного обеспечения и сопутствующей документации
|
||||
(в дальнейшем именуемыми «Программное Обеспечение»), безвозмездно
|
||||
использовать Программное Обеспечение без ограничений, включая
|
||||
неограниченное право на использование, копирование, изменение,
|
||||
добавление, публикацию, распространение, сублицензирование
|
||||
и/или продажу копий Программного Обеспечения, также как и лицам,
|
||||
которым предоставляется данное Программное Обеспечение,
|
||||
при соблюдении следующих условий:
|
||||
|
||||
Указанное выше уведомление об авторском праве и данные условия
|
||||
должны быть включены во все копии или значимые части данного
|
||||
Программного Обеспечения.
|
||||
|
||||
ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ»,
|
||||
БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ,
|
||||
ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ,
|
||||
СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ
|
||||
ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ
|
||||
ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ
|
||||
ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ,
|
||||
ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ
|
||||
ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
|
||||
ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
21
node_modules/svgo/Makefile
generated
vendored
21
node_modules/svgo/Makefile
generated
vendored
@@ -1,21 +0,0 @@
|
||||
test:
|
||||
@NODE_ENV=test ./node_modules/.bin/mocha
|
||||
|
||||
lib-cov:
|
||||
@./node_modules/.bin/istanbul instrument --output lib-cov --no-compact --variable global.__coverage__ lib
|
||||
|
||||
coverage: lib-cov
|
||||
@COVERAGE=1 ISTANBUL_REPORTERS=text-summary ./node_modules/.bin/mocha --reporter mocha-istanbul
|
||||
@rm -rf lib-cov
|
||||
|
||||
coveralls: lib-cov
|
||||
@COVERAGE=1 ISTANBUL_REPORTERS=lcovonly ./node_modules/.bin/mocha --reporter mocha-istanbul
|
||||
@cat lcov.info | ./node_modules/.bin/coveralls
|
||||
@rm -rf lib-cov lcov.info
|
||||
|
||||
travis: jshint test coveralls
|
||||
|
||||
jshint:
|
||||
@jshint --show-non-errors .
|
||||
|
||||
.PHONY: test
|
||||
368
node_modules/svgo/README.md
generated
vendored
368
node_modules/svgo/README.md
generated
vendored
@@ -1,150 +1,294 @@
|
||||
**english** | [русский](https://github.com/svg/svgo/blob/master/README.ru.md)
|
||||
- - -
|
||||
<div align="center">
|
||||
<img src="./logo/logo-web.svg" width="348.61" height="100" alt="SVGO logo"/>
|
||||
</div>
|
||||
|
||||
<img src="https://svg.github.io/svgo-logo.svg" width="200" height="200" alt="logo"/>
|
||||
## SVGO [](https://npmjs.org/package/svgo) [](https://discord.gg/z8jX8NYxrE)
|
||||
|
||||
## SVGO [](https://npmjs.org/package/svgo) [](https://gemnasium.com/svg/svgo) [](https://travis-ci.org/svg/svgo) [](https://coveralls.io/r/svg/svgo?branch=master)
|
||||
|
||||
**SVG O**ptimizer is a Nodejs-based tool for optimizing SVG vector graphics files.
|
||||

|
||||
**SVG O**ptimizer is a Node.js-based tool for optimizing SVG vector graphics files.
|
||||
|
||||
## Why?
|
||||
|
||||
SVG files, especially exported from various editors, usually contain a lot of redundant and useless information such as editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting SVG rendering result.
|
||||
SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result.
|
||||
|
||||
## What it can do
|
||||
|
||||
SVGO has a plugin-based architecture, so almost every optimization is a separate plugin.
|
||||
|
||||
Today we have:
|
||||
|
||||
* [ [ cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) ] cleanup attributes from newlines, trailing and repeating spaces
|
||||
* [ [ removeDoctype](https://github.com/svg/svgo/blob/master/plugins/removeDoctype.js) ] remove doctype declaration
|
||||
* [ [ removeXMLProcInst](https://github.com/svg/svgo/blob/master/plugins/removeXMLProcInst.js) ] remove XML processing instructions
|
||||
* [ [ removeComments](https://github.com/svg/svgo/blob/master/plugins/removeComments.js) ] remove comments
|
||||
* [ [ removeMetadata](https://github.com/svg/svgo/blob/master/plugins/removeMetadata.js) ] remove `<metadata>`
|
||||
* [ [ removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) ] remove `<title>` (disabled by default)
|
||||
* [ [ removeDesc](https://github.com/svg/svgo/blob/master/plugins/removeDesc.js) ] remove `<desc>` (only non-meaningful by default)
|
||||
* [ [ removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) ] remove elements of `<defs>` without `id`
|
||||
* [ [ removeEditorsNSData](https://github.com/svg/svgo/blob/master/plugins/removeEditorsNSData.js) ] remove editors namespaces, elements and attributes
|
||||
* [ [ removeEmptyAttrs](https://github.com/svg/svgo/blob/master/plugins/removeEmptyAttrs.js) ] remove empty attributes
|
||||
* [ [ removeHiddenElems](https://github.com/svg/svgo/blob/master/plugins/removeHiddenElems.js) ] remove hidden elements
|
||||
* [ [ removeEmptyText](https://github.com/svg/svgo/blob/master/plugins/removeEmptyText.js) ] remove empty Text elements
|
||||
* [ [ removeEmptyContainers](https://github.com/svg/svgo/blob/master/plugins/removeEmptyContainers.js) ] remove empty Container elements
|
||||
* [ [ removeViewBox](https://github.com/svg/svgo/blob/master/plugins/removeViewBox.js) ] remove `viewBox` attribute when possible (disabled by default)
|
||||
* [ [ cleanUpEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) ] remove or cleanup `enable-background` attribute when possible
|
||||
* [ [ minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js) ] minify `<style>` elements content with [CSSO](https://github.com/css/csso)
|
||||
* [ [ convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js) ] convert styles into attributes
|
||||
* [ [ convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) ] convert colors (from `rgb()` to `#rrggbb`, from `#rrggbb` to `#rgb`)
|
||||
* [ [ convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js) ] convert Path data to relative or absolute whichever is shorter, convert one segment to another, trim useless delimiters, smart rounding and much more
|
||||
* [ [ convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js) ] collapse multiple transforms into one, convert matrices to the short aliases and much more
|
||||
* [ [ removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) ] remove unknown elements content and attributes, remove attrs with default values
|
||||
* [ [ removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) ] remove non-inheritable group's "presentation" attributes
|
||||
* [ [ removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) ] remove useless stroke and fill attrs
|
||||
* [ [ removeUnusedNS](https://github.com/svg/svgo/blob/master/plugins/removeUnusedNS.js) ] remove unused namespaces declaration
|
||||
* [ [ cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) ] remove unused and minify used IDs
|
||||
* [ [ cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) ] round numeric values to the fixed precision, remove default 'px' units
|
||||
* [ [ cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) ] round numeric values in attributes that take a list of numbers, like `viewBox` or `enableBackground`
|
||||
* [ [ moveElemsAttrsToGroup](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup.js) ] move elements attributes to the existing group wrapper
|
||||
* [ [ moveGroupAttrsToElems](https://github.com/svg/svgo/blob/master/plugins/moveGroupAttrsToElems.js) ] move some group attributes to the content elements
|
||||
* [ [ collapseGroups](https://github.com/svg/svgo/blob/master/plugins/collapseGroups.js) ] collapse useless groups
|
||||
* [ [ removeRasterImages](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) ] remove raster images (disabled by default)
|
||||
* [ [ mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) ] merge multiple Paths into one
|
||||
* [ [ convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) ] convert some basic shapes to path
|
||||
* [ [ sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) ] sort element attributes for epic readability (disabled by default)
|
||||
* [ [ transformsWithOnePath](https://github.com/svg/svgo/blob/master/plugins/transformsWithOnePath.js) ] apply transforms, crop by real width, center vertical alignment and resize SVG with one Path inside (disabled by default)
|
||||
* [ [ removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) ] remove width/height attributes if viewBox is present (disabled by default)
|
||||
* [ [ removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) ] remove attributes by pattern (disabled by default)
|
||||
* [ [ addClassesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addClassesToSVGElement.js) ] add classnames to an outer `<svg>` element (disabled by default)
|
||||
* [ [ removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js) ] remove `<style>` elements (disabled by default)
|
||||
|
||||
Want to know how it works and how to write your own plugin? [Of course you want to](https://github.com/svg/svgo/blob/master/docs/how-it-works/en.md).
|
||||
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ [sudo] npm install -g svgo
|
||||
npm -g install svgo
|
||||
```
|
||||
|
||||
```
|
||||
Usage:
|
||||
svgo [OPTIONS] [ARGS]
|
||||
or
|
||||
|
||||
Options:
|
||||
-h, --help : Help
|
||||
-v, --version : Version
|
||||
-i INPUT, --input=INPUT : Input file, "-" for STDIN
|
||||
-s STRING, --string=STRING : Input SVG data string
|
||||
-f FOLDER, --folder=FOLDER : Input folder, optimize and rewrite all *.svg files
|
||||
-o OUTPUT, --output=OUTPUT : Output file or folder (by default the same as the input), "-" for STDOUT
|
||||
-p PRECISION, --precision=PRECISION : Set number of digits in the fractional part, overrides plugins params
|
||||
--config=CONFIG : Config file to extend or replace default
|
||||
--disable=DISABLE : Disable plugin by name
|
||||
--enable=ENABLE : Enable plugin by name
|
||||
--datauri=DATAURI : Output as Data URI string (base64, URI encoded or unencoded)
|
||||
-q, --quiet : Only output error messages, not regular status messages
|
||||
--pretty : Make SVG pretty printed
|
||||
--show-plugins : Show available plugins and exit
|
||||
|
||||
Arguments:
|
||||
INPUT : Alias to --input
|
||||
OUTPUT : Alias to --output
|
||||
```sh
|
||||
yarn global add svgo
|
||||
```
|
||||
|
||||
* with files:
|
||||
## CLI usage
|
||||
|
||||
$ svgo test.svg
|
||||
```sh
|
||||
svgo one.svg two.svg -o one.min.svg two.min.svg
|
||||
```
|
||||
|
||||
or:
|
||||
Or use the `--folder`/`-f` flag to optimize a whole folder of SVG icons
|
||||
|
||||
$ svgo test.svg test.min.svg
|
||||
```sh
|
||||
svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output
|
||||
```
|
||||
|
||||
* with STDIN / STDOUT:
|
||||
See help for advanced usage
|
||||
|
||||
$ cat test.svg | svgo -i - -o - > test.min.svg
|
||||
```sh
|
||||
svgo --help
|
||||
```
|
||||
|
||||
* with folder
|
||||
## Configuration
|
||||
|
||||
$ svgo -f ../path/to/folder/with/svg/files
|
||||
Some options can be configured with CLI though it may be easier to have the configuration in a separate file.
|
||||
SVGO automatically loads configuration from `svgo.config.js` or module specified with `--config` flag.
|
||||
|
||||
or:
|
||||
```js
|
||||
module.exports = {
|
||||
multipass: true, // boolean. false by default
|
||||
datauri: 'enc', // 'base64', 'enc' or 'unenc'. 'base64' by default
|
||||
js2svg: {
|
||||
indent: 2, // string with spaces or number of spaces. 4 by default
|
||||
pretty: true, // boolean, false by default
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
$ svgo -f ../path/to/folder/with/svg/files -o ../path/to/folder/with/svg/output
|
||||
SVGO has a plugin-based architecture, so almost every optimization is a separate plugin.
|
||||
There is a set of [built-in plugins](#built-in-plugins). See how to configure them:
|
||||
|
||||
* with strings:
|
||||
```js
|
||||
module.exports = {
|
||||
plugins: [
|
||||
// enable a built-in plugin by name
|
||||
'prefixIds',
|
||||
|
||||
$ svgo -s '<svg version="1.1">test</svg>' -o test.min.svg
|
||||
// or by expanded version
|
||||
{
|
||||
name: 'prefixIds',
|
||||
},
|
||||
|
||||
or even with Data URI base64:
|
||||
// some plugins allow/require to pass options
|
||||
{
|
||||
name: 'prefixIds',
|
||||
params: {
|
||||
prefix: 'my-prefix',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
$ svgo -s 'data:image/svg+xml;base64,…' -o test.min.svg
|
||||
The default preset of plugins is fully overridden if the `plugins` field is specified.
|
||||
Use `preset-default` plugin to customize plugins options.
|
||||
|
||||
* with SVGZ:
|
||||
```js
|
||||
module.exports = {
|
||||
plugins: [
|
||||
{
|
||||
name: 'preset-default',
|
||||
params: {
|
||||
overrides: {
|
||||
// customize options for plugins included in preset
|
||||
inlineStyles: {
|
||||
onlyMatchedOnce: false,
|
||||
},
|
||||
|
||||
from `.svgz` to `.svg`:
|
||||
// or disable plugins
|
||||
removeDoctype: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
$ gunzip -c test.svgz | svgo -i - -o test.min.svg
|
||||
// enable builtin plugin not included in default preset
|
||||
'prefixIds',
|
||||
|
||||
from `.svg` to `.svgz`:
|
||||
// enable and configure builtin plugin not included in preset
|
||||
{
|
||||
name: 'sortAttrs',
|
||||
params: {
|
||||
xmlnsOrder: 'alphabetical',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
$ svgo test.svg -o - | gzip -cfq9 > test.svgz
|
||||
Default preset includes the following list of plugins:
|
||||
|
||||
* with GUI – [svgo-gui](https://github.com/svg/svgo-gui)
|
||||
* as a web app - [SVGOMG](https://jakearchibald.github.io/svgomg/)
|
||||
* as a Nodejs module – [examples](https://github.com/svg/svgo/tree/master/examples)
|
||||
* as a Grunt task – [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin)
|
||||
* as a Gulp task – [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin)
|
||||
* as a Mimosa module – [mimosa-minify-svg](https://github.com/dbashford/mimosa-minify-svg)
|
||||
* as an OSX Folder Action – [svgo-osx-folder-action](https://github.com/svg/svgo-osx-folder-action)
|
||||
* as a webpack loader – [image-webpack-loader](https://github.com/tcoopman/image-webpack-loader)
|
||||
- removeDoctype
|
||||
- removeXMLProcInst
|
||||
- removeComments
|
||||
- removeMetadata
|
||||
- removeEditorsNSData
|
||||
- cleanupAttrs
|
||||
- mergeStyles
|
||||
- inlineStyles
|
||||
- minifyStyles
|
||||
- cleanupIDs
|
||||
- removeUselessDefs
|
||||
- cleanupNumericValues
|
||||
- convertColors
|
||||
- removeUnknownsAndDefaults
|
||||
- removeNonInheritableGroupAttrs
|
||||
- removeUselessStrokeAndFill
|
||||
- removeViewBox
|
||||
- cleanupEnableBackground
|
||||
- removeHiddenElems
|
||||
- removeEmptyText
|
||||
- convertShapeToPath
|
||||
- convertEllipseToCircle
|
||||
- moveElemsAttrsToGroup
|
||||
- moveGroupAttrsToElems
|
||||
- collapseGroups
|
||||
- convertPathData
|
||||
- convertTransform
|
||||
- removeEmptyAttrs
|
||||
- removeEmptyContainers
|
||||
- mergePaths
|
||||
- removeUnusedNS
|
||||
- sortDefsChildren
|
||||
- removeTitle
|
||||
- removeDesc
|
||||
|
||||
## Donate
|
||||
It's also possible to specify a custom plugin:
|
||||
|
||||
BTC `1zVZYqRSzQ4aaL27rp3PLwFFSXpfs5H8r`
|
||||
```js
|
||||
const anotherCustomPlugin = require('./another-custom-plugin.js');
|
||||
module.exports = {
|
||||
plugins: [
|
||||
{
|
||||
name: 'customPluginName',
|
||||
type: 'perItem', // 'perItem', 'perItemReverse' or 'full'
|
||||
params: {
|
||||
optionName: 'optionValue',
|
||||
},
|
||||
fn: (ast, params, info) => {},
|
||||
},
|
||||
anotherCustomPlugin,
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## License and copyrights
|
||||
## API usage
|
||||
|
||||
SVGO provides a few low level utilities.
|
||||
|
||||
### optimize
|
||||
|
||||
The core of SVGO is `optimize` function.
|
||||
|
||||
```js
|
||||
const { optimize } = require('svgo');
|
||||
const result = optimize(svgString, {
|
||||
// optional but recommended field
|
||||
path: 'path-to.svg',
|
||||
// all config fields are also available here
|
||||
multipass: true,
|
||||
});
|
||||
const optimizedSvgString = result.data;
|
||||
```
|
||||
|
||||
### loadConfig
|
||||
|
||||
If you write a tool on top of SVGO you might need a way to load SVGO config.
|
||||
|
||||
```js
|
||||
const { loadConfig } = require('svgo');
|
||||
const config = await loadConfig();
|
||||
|
||||
// you can also specify a relative or absolute path and customize the current working directory
|
||||
const config = await loadConfig(configFile, cwd);
|
||||
```
|
||||
|
||||
## Built-in plugins
|
||||
|
||||
| Plugin | Description | Default |
|
||||
| ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
|
||||
| [cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) | cleanup attributes from newlines, trailing, and repeating spaces | `enabled` |
|
||||
| [mergeStyles](https://github.com/svg/svgo/blob/master/plugins/mergeStyles.js) | merge multiple style elements into one | `enabled` |
|
||||
| [inlineStyles](https://github.com/svg/svgo/blob/master/plugins/inlineStyles.js) | move and merge styles from `<style>` elements to element `style` attributes | `enabled` |
|
||||
| [removeDoctype](https://github.com/svg/svgo/blob/master/plugins/removeDoctype.js) | remove `doctype` declaration | `enabled` |
|
||||
| [removeXMLProcInst](https://github.com/svg/svgo/blob/master/plugins/removeXMLProcInst.js) | remove XML processing instructions | `enabled` |
|
||||
| [removeComments](https://github.com/svg/svgo/blob/master/plugins/removeComments.js) | remove comments | `enabled` |
|
||||
| [removeMetadata](https://github.com/svg/svgo/blob/master/plugins/removeMetadata.js) | remove `<metadata>` | `enabled` |
|
||||
| [removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) | remove `<title>` | `enabled` |
|
||||
| [removeDesc](https://github.com/svg/svgo/blob/master/plugins/removeDesc.js) | remove `<desc>` | `enabled` |
|
||||
| [removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) | remove elements of `<defs>` without `id` | `enabled` |
|
||||
| [removeXMLNS](https://github.com/svg/svgo/blob/master/plugins/removeXMLNS.js) | removes the `xmlns` attribute (for inline SVG) | `disabled` |
|
||||
| [removeEditorsNSData](https://github.com/svg/svgo/blob/master/plugins/removeEditorsNSData.js) | remove editors namespaces, elements, and attributes | `enabled` |
|
||||
| [removeEmptyAttrs](https://github.com/svg/svgo/blob/master/plugins/removeEmptyAttrs.js) | remove empty attributes | `enabled` |
|
||||
| [removeHiddenElems](https://github.com/svg/svgo/blob/master/plugins/removeHiddenElems.js) | remove hidden elements | `enabled` |
|
||||
| [removeEmptyText](https://github.com/svg/svgo/blob/master/plugins/removeEmptyText.js) | remove empty Text elements | `enabled` |
|
||||
| [removeEmptyContainers](https://github.com/svg/svgo/blob/master/plugins/removeEmptyContainers.js) | remove empty Container elements | `enabled` |
|
||||
| [removeViewBox](https://github.com/svg/svgo/blob/master/plugins/removeViewBox.js) | remove `viewBox` attribute when possible | `enabled` |
|
||||
| [cleanupEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) | remove or cleanup `enable-background` attribute when possible | `enabled` |
|
||||
| [minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js) | minify `<style>` elements content with [CSSO](https://github.com/css/csso) | `enabled` |
|
||||
| [convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js) | convert styles into attributes | `disabled` |
|
||||
| [convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) | convert colors (from `rgb()` to `#rrggbb`, from `#rrggbb` to `#rgb`) | `enabled` |
|
||||
| [convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js) | convert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much more | `enabled` |
|
||||
| [convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js) | collapse multiple transforms into one, convert matrices to the short aliases, and much more | `enabled` |
|
||||
| [removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) | remove unknown elements content and attributes, remove attributes with default values | `enabled` |
|
||||
| [removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) | remove non-inheritable group's "presentation" attributes | `enabled` |
|
||||
| [removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) | remove useless `stroke` and `fill` attributes | `enabled` |
|
||||
| [removeUnusedNS](https://github.com/svg/svgo/blob/master/plugins/removeUnusedNS.js) | remove unused namespaces declaration | `enabled` |
|
||||
| [prefixIds](https://github.com/svg/svgo/blob/master/plugins/prefixIds.js) | prefix IDs and classes with the SVG filename or an arbitrary string | `disabled` |
|
||||
| [cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) | remove unused and minify used IDs | `enabled` |
|
||||
| [cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) | round numeric values to the fixed precision, remove default `px` units | `enabled` |
|
||||
| [cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) | round numeric values in attributes that take a list of numbers (like `viewBox` or `enable-background`) | `disabled` |
|
||||
| [moveElemsAttrsToGroup](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup.js) | move elements' attributes to their enclosing group | `enabled` |
|
||||
| [moveGroupAttrsToElems](https://github.com/svg/svgo/blob/master/plugins/moveGroupAttrsToElems.js) | move some group attributes to the contained elements | `enabled` |
|
||||
| [collapseGroups](https://github.com/svg/svgo/blob/master/plugins/collapseGroups.js) | collapse useless groups | `enabled` |
|
||||
| [removeRasterImages](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) | remove raster images | `disabled` |
|
||||
| [mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) | merge multiple Paths into one | `enabled` |
|
||||
| [convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) | convert some basic shapes to `<path>` | `enabled` |
|
||||
| [convertEllipseToCircle](https://github.com/svg/svgo/blob/master/plugins/convertEllipseToCircle.js) | convert non-eccentric `<ellipse>` to `<circle>` | `enabled` |
|
||||
| [sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) | sort element attributes for epic readability | `disabled` |
|
||||
| [sortDefsChildren](https://github.com/svg/svgo/blob/master/plugins/sortDefsChildren.js) | sort children of `<defs>` in order to improve compression | `enabled` |
|
||||
| [removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) | remove `width`/`height` and add `viewBox` if it's missing (opposite to removeViewBox, disable it first) | `disabled` |
|
||||
| [removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) | remove attributes by pattern | `disabled` |
|
||||
| [removeAttributesBySelector](https://github.com/svg/svgo/blob/master/plugins/removeAttributesBySelector.js) | removes attributes of elements that match a CSS selector | `disabled` |
|
||||
| [removeElementsByAttr](https://github.com/svg/svgo/blob/master/plugins/removeElementsByAttr.js) | remove arbitrary elements by `ID` or `className` | `disabled` |
|
||||
| [addClassesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addClassesToSVGElement.js) | add classnames to an outer `<svg>` element | `disabled` |
|
||||
| [addAttributesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addAttributesToSVGElement.js) | adds attributes to an outer `<svg>` element | `disabled` |
|
||||
| [removeOffCanvasPaths](https://github.com/svg/svgo/blob/master/plugins/removeOffCanvasPaths.js) | removes elements that are drawn outside of the viewbox | `disabled` |
|
||||
| [removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js) | remove `<style>` elements | `disabled` |
|
||||
| [removeScriptElement](https://github.com/svg/svgo/blob/master/plugins/removeScriptElement.js) | remove `<script>` elements | `disabled` |
|
||||
| [reusePaths](https://github.com/svg/svgo/blob/master/plugins/reusePaths.js) | Find duplicated <path> elements and replace them with <use> links | `disabled` |
|
||||
|
||||
## Other Ways to Use SVGO
|
||||
|
||||
- as a web app – [SVGOMG](https://jakearchibald.github.io/svgomg/)
|
||||
- as a GitHub Action – [SVGO Action](https://github.com/marketplace/actions/svgo-action)
|
||||
- as a Grunt task – [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin)
|
||||
- as a Gulp task – [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin)
|
||||
- as a Mimosa module – [mimosa-minify-svg](https://github.com/dbashford/mimosa-minify-svg)
|
||||
- as an OSX Folder Action – [svgo-osx-folder-action](https://github.com/svg/svgo-osx-folder-action)
|
||||
- as a webpack loader – [image-webpack-loader](https://github.com/tcoopman/image-webpack-loader)
|
||||
- as a Telegram Bot – [svgo_bot](https://github.com/maksugr/svgo_bot)
|
||||
- as a PostCSS plugin – [postcss-svgo](https://github.com/ben-eb/postcss-svgo)
|
||||
- as an Inkscape plugin – [inkscape-svgo](https://github.com/konsumer/inkscape-svgo)
|
||||
- as a Sketch plugin - [svgo-compressor](https://github.com/BohemianCoding/svgo-compressor)
|
||||
- as a macOS app - [Image Shrinker](https://image-shrinker.com)
|
||||
- as a Rollup plugin - [rollup-plugin-svgo](https://github.com/porsager/rollup-plugin-svgo)
|
||||
- as a VS Code plugin - [vscode-svgo](https://github.com/1000ch/vscode-svgo)
|
||||
- as a Atom plugin - [atom-svgo](https://github.com/1000ch/atom-svgo)
|
||||
- as a Sublime plugin - [Sublime-svgo](https://github.com/1000ch/Sublime-svgo)
|
||||
- as a Figma plugin - [Advanced SVG Export](https://www.figma.com/c/plugin/782713260363070260/Advanced-SVG-Export)
|
||||
- as a Linux app - [Oh My SVG](https://github.com/sonnyp/OhMySVG)
|
||||
- as a Browser extension - [SVG Gobbler](https://github.com/rossmoody/svg-gobbler)
|
||||
- as an API - [Vector Express](https://github.com/smidyo/vectorexpress-api#convertor-svgo)
|
||||
|
||||
## Donators
|
||||
|
||||
| [<img src="https://sheetjs.com/sketch128.png" width="80">](https://sheetjs.com/) | [<img src="https://raw.githubusercontent.com/fontello/fontello/master/fontello-image.svg" width="80">](https://fontello.com/) |
|
||||
| :------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------: |
|
||||
| [SheetJS LLC](https://sheetjs.com/) | [Fontello](https://fontello.com/) |
|
||||
|
||||
## License and Copyright
|
||||
|
||||
This software is released under the terms of the [MIT license](https://github.com/svg/svgo/blob/master/LICENSE).
|
||||
|
||||
Logo by [Yegor Bolshakov](http://xizzzy.ru/).
|
||||
Logo by [André Castillo](https://github.com/DerianAndre).
|
||||
|
||||
149
node_modules/svgo/README.ru.md
generated
vendored
149
node_modules/svgo/README.ru.md
generated
vendored
@@ -1,149 +0,0 @@
|
||||
[english](https://github.com/svg/svgo/blob/master/README.md) | **русский**
|
||||
- - -
|
||||
|
||||
<img src="https://svg.github.io/svgo-logo.svg" width="200" height="200" alt="logo"/>
|
||||
|
||||
## SVGO [](https://npmjs.org/package/svgo) [](https://gemnasium.com/svg/svgo) [](https://travis-ci.org/svg/svgo) [](https://coveralls.io/r/svg/svgo?branch=master)
|
||||
|
||||
**SVG** **O**ptimizer – это инструмент для оптимизации векторной графики в формате SVG, написанный на Node.js.
|
||||

|
||||
|
||||
## Зачем?
|
||||
|
||||
SVG-файлы, особенно – экспортированные из различных редакторов, содержат много избыточной и бесполезной информации, комментариев, скрытых элементов, неоптимальные или стандартные значения и другой мусор, удаление которого безопасно и не влияет на конечный результат отрисовки.
|
||||
|
||||
## Возможности
|
||||
|
||||
SVGO имеет расширяемую архитектуру, в которой почти каждая оптимизация является отдельным расширением.
|
||||
|
||||
Сегодня у нас есть:
|
||||
|
||||
* [ [ cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) ] удаление переносов строк и лишних пробелов
|
||||
* [ [ removeDoctype](https://github.com/svg/svgo/blob/master/plugins/removeDoctype.js) ] удаление doctype
|
||||
* [ [ removeXMLProcInst](https://github.com/svg/svgo/blob/master/plugins/removeXMLProcInst.js) ] удаление XML-инструкций
|
||||
* [ [ removeComments](https://github.com/svg/svgo/blob/master/plugins/removeComments.js) ] удаление комментариев
|
||||
* [ [ removeMetadata](https://github.com/svg/svgo/blob/master/plugins/removeMetadata.js) ] удаление `<metadata>`
|
||||
* [ [ removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) ] удаление `<title>` (отключена по умолчанию)
|
||||
* [ [ removeDesc](https://github.com/svg/svgo/blob/master/plugins/removeDesc.js) ] удаление `<desc>` (по умолчанию только незначимых)
|
||||
* [ [ removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) ] удаление элементов в `<defs>` без `id`
|
||||
* [ [ removeEditorsNSData](https://github.com/svg/svgo/blob/master/plugins/removeEditorsNSData.js) ] удаление пространств имён различных редакторов, их элементов и атрибутов
|
||||
* [ [ removeEmptyAttrs](https://github.com/svg/svgo/blob/master/plugins/removeEmptyAttrs.js) ] удаление пустых атрибутов
|
||||
* [ [ removeHiddenElems](https://github.com/svg/svgo/blob/master/plugins/removeHiddenElems.js) ] удаление скрытых элементов
|
||||
* [ [ removeEmptyText](https://github.com/svg/svgo/blob/master/plugins/removeEmptyText.js) ] удаление пустых текстовых элементов
|
||||
* [ [ removeEmptyContainers](https://github.com/svg/svgo/blob/master/plugins/removeEmptyContainers.js) ] удаление пустых элементов-контейнеров
|
||||
* [ [ removeViewBox](https://github.com/svg/svgo/blob/master/plugins/removeViewBox.js) ] удаление атрибута `viewBox`, когда это возможно
|
||||
* [ [ cleanupEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) ] удаление или оптимизация атрибута `enable-background`, когда это возможно
|
||||
* [ [ minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js) ] уменьшает содержимое элементов `<style>` с помощью [CSSO](https://github.com/css/csso).
|
||||
* [ [ convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js) ] конвертирование стилей в атрибуте `style` в отдельные svg-атрибуты
|
||||
* [ [ convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) ] конвертирование цветовых значений: из `rgb()` в `#rrggbb`, из `#rrggbb` в `#rgb`
|
||||
* [ [ convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js) ] конвертирование данных Path в относительные или абсолютные координаты, смотря что короче, конвертирование одних типов сегментов в другие, удаление ненужных разделителей, умное округление и тому подобное
|
||||
* [ [ convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js) ] схлопывание нескольких трансформаций в одну, конвертирование матриц в короткие алиасы и многое другое
|
||||
* [ [ removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) ] удаление неизвестных элементов, контента и атрибутов
|
||||
* [ [ removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) ] удаление ненаследуемых "презентационных" атрибутов групп
|
||||
* [ [ removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) ] удаление неиспользуемых атрибутов stroke-* и fill-*
|
||||
* [ [ removeUnusedNS](https://github.com/svg/svgo/blob/master/plugins/removeUnusedNS.js) ] удаление деклараций неиспользуемых пространств имён
|
||||
* [ [ cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) ] удаление неиспользуемых и сокращение используемых ID
|
||||
* [ [ cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) ] округление дробных чисел до заданной точности, удаление `px` как единицы измерения по-умолчанию
|
||||
* [ [ cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) ] округление числовых значений в атрибутах со списком чисел, таких как `viewBox` или `enableBackground`
|
||||
* [ [ moveElemsAttrsToGroup](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup.js) ] перемещение совпадающих атрибутов у всех элементов внутри группы `<g>`
|
||||
* [ [ moveGroupAttrsToElems](https://github.com/svg/svgo/blob/master/plugins/moveGroupAttrsToElems.js) ] перемещение некоторых атрибутов группы на элементы внутри
|
||||
* [ [ collapseGroups](https://github.com/svg/svgo/blob/master/plugins/collapseGroups.js) ] схлопывание бесполезных групп `<g>`
|
||||
* [ [ removeRasterImage](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) ] удаление растровых изображений (выключено по умолчанию)
|
||||
* [ [ mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) ] склеивание нескольких Path в одну кривую
|
||||
* [ [ convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) ] конвертирование простых форм в Path
|
||||
* [ [ sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) ] сортировка атрибутов элементов для удобочитаемости (выключено по умолчанию)
|
||||
* [ [ transformsWithOnePath](https://github.com/svg/svgo/blob/master/plugins/transformsWithOnePath.js) ] применение трансформаций, обрезка по реальной ширине, вертикальное выравнивание по центру и изменение размеров SVG с одним Path внутри
|
||||
* [ [ removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) ] удаляет атрибуты width/height при наличии viewBox (выключено по умолчанию)
|
||||
* [ [ removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) ] удаляет атрибуты по указанному паттерну (выключено по умолчанию)
|
||||
* [ [ addClassesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addClassesToSVGElement.js) ] добавляет имена классов корневому элементу `<svg>` (выключено по умолчанию)
|
||||
* [ [ removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js) ] удаляет элементы `<style>` (выключено по умолчанию)
|
||||
|
||||
Хотите узнать, как это работает и как написать свой плагин? [Конечно же, да!](https://github.com/svg/svgo/blob/master/docs/how-it-works/ru.md).
|
||||
|
||||
|
||||
## Как использовать
|
||||
|
||||
```sh
|
||||
$ [sudo] npm install -g svgo
|
||||
```
|
||||
|
||||
```
|
||||
Выполнение:
|
||||
svgo [OPTIONS] [ARGS]
|
||||
|
||||
Параметры:
|
||||
-h, --help : Помощь
|
||||
-v, --version : Версия программы
|
||||
-i INPUT, --input=INPUT : Входной файл, "-" для STDIN
|
||||
-s STRING, --string=STRING : Входная строка SVG
|
||||
-f FOLDER, --folder=FOLDER : Входная папка, оптимизирует и перезаписывает все файлы *.svg
|
||||
-o OUTPUT, --output=OUTPUT : Выходной файл или папка (совпадает с входным по умолчанию), "-" для STDOUT
|
||||
-p PRECISION, --precision=PRECISION : Число цифр после запятой, переопределяет параметры плагинов
|
||||
--config=CONFIG : Файл конфигурации для расширения и замены настроек
|
||||
--disable=DISABLE : Выключение плагина по имени
|
||||
--enable=ENABLE : Включение плагина по имени
|
||||
--datauri=DATAURI : Результат в виде строки Data URI (base64, URI encoded или unencoded)
|
||||
-q, --quiet : Подавляет вывод информации, выводятся только сообщения об ошибках
|
||||
--pretty : Удобочитаемое форматирование SVG
|
||||
--show-plugins : Доступные плагины
|
||||
|
||||
Аргументы:
|
||||
INPUT : Аналогично --input
|
||||
OUTPUT : Аналогично --output
|
||||
```
|
||||
|
||||
* с файлами:
|
||||
|
||||
$ svgo test.svg
|
||||
|
||||
или:
|
||||
|
||||
$ svgo test.svg test.min.svg
|
||||
|
||||
* со STDIN / STDOUT:
|
||||
|
||||
$ cat test.svg | svgo -i - -o - > test.min.svg
|
||||
|
||||
* с папками
|
||||
|
||||
$ svgo -f ../path/to/folder/with/svg/files
|
||||
|
||||
или:
|
||||
|
||||
$ svgo -f ../path/to/folder/with/svg/files -o ../path/to/folder/with/svg/output
|
||||
|
||||
* со строками:
|
||||
|
||||
$ svgo -s '<svg version="1.1">test</svg>' -o test.min.svg
|
||||
|
||||
или даже с Data URI base64:
|
||||
|
||||
$ svgo -s 'data:image/svg+xml;base64,…' -o test.min.svg
|
||||
|
||||
* с SVGZ:
|
||||
|
||||
из `.svgz` в `.svg`:
|
||||
|
||||
$ gunzip -c test.svgz | svgo -i - -o test.min.svg
|
||||
|
||||
из `.svg` в `.svgz`:
|
||||
|
||||
$ svgo test.svg -o - | gzip -cfq9 > test.svgz
|
||||
|
||||
* с помощью GUI – [svgo-gui](https://github.com/svg/svgo-gui)
|
||||
* в виде веб-приложения - [SVGOMG](https://jakearchibald.github.io/svgomg/)
|
||||
* как модуль Node.js – [examples](https://github.com/svg/svgo/tree/master/examples)
|
||||
* как таск для Grunt – [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin)
|
||||
* как таск для Gulp – [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin)
|
||||
* как таск для Mimosa – [mimosa-minify-svg](https://github.com/dbashford/mimosa-minify-svg)
|
||||
* как действие папки в OSX – [svgo-osx-folder-action](https://github.com/svg/svgo-osx-folder-action)
|
||||
|
||||
## Пожертвования
|
||||
|
||||
BTC `1zVZYqRSzQ4aaL27rp3PLwFFSXpfs5H8r`
|
||||
|
||||
## Лицензия и копирайты
|
||||
|
||||
Данное программное обеспечение выпускается под [лицензией MIT](https://github.com/svg/svgo/blob/master/LICENSE).
|
||||
|
||||
Логотип – [Егор Большаков](http://xizzzy.ru/).
|
||||
9
node_modules/svgo/bin/svgo
generated
vendored
9
node_modules/svgo/bin/svgo
generated
vendored
@@ -1,3 +1,10 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
require('../lib/svgo/coa').run();
|
||||
const colors = require('picocolors');
|
||||
const { program } = require('commander');
|
||||
const makeProgram = require('../lib/svgo/coa');
|
||||
makeProgram(program);
|
||||
program.parseAsync(process.argv).catch(error => {
|
||||
console.error(colors.red(error.stack));
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
1
node_modules/svgo/dist/svgo.browser.js
generated
vendored
Normal file
1
node_modules/svgo/dist/svgo.browser.js
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
239
node_modules/svgo/lib/css-tools.js
generated
vendored
Normal file
239
node_modules/svgo/lib/css-tools.js
generated
vendored
Normal file
@@ -0,0 +1,239 @@
|
||||
'use strict';
|
||||
|
||||
var csstree = require('css-tree'),
|
||||
List = csstree.List,
|
||||
stable = require('stable'),
|
||||
specificity = require('csso/lib/restructure/prepare/specificity');
|
||||
|
||||
/**
|
||||
* Flatten a CSS AST to a selectors list.
|
||||
*
|
||||
* @param {import('css-tree').CssNode} cssAst css-tree AST to flatten
|
||||
* @return {Array} selectors
|
||||
*/
|
||||
function flattenToSelectors(cssAst) {
|
||||
var selectors = [];
|
||||
|
||||
csstree.walk(cssAst, {
|
||||
visit: 'Rule',
|
||||
enter: function (node) {
|
||||
if (node.type !== 'Rule') {
|
||||
return;
|
||||
}
|
||||
|
||||
var atrule = this.atrule;
|
||||
var rule = node;
|
||||
|
||||
node.prelude.children.each(function (selectorNode, selectorItem) {
|
||||
var selector = {
|
||||
item: selectorItem,
|
||||
atrule: atrule,
|
||||
rule: rule,
|
||||
pseudos: /** @type {{item: any; list: any[]}[]} */ ([]),
|
||||
};
|
||||
|
||||
selectorNode.children.each(function (
|
||||
selectorChildNode,
|
||||
selectorChildItem,
|
||||
selectorChildList
|
||||
) {
|
||||
if (
|
||||
selectorChildNode.type === 'PseudoClassSelector' ||
|
||||
selectorChildNode.type === 'PseudoElementSelector'
|
||||
) {
|
||||
selector.pseudos.push({
|
||||
item: selectorChildItem,
|
||||
list: selectorChildList,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
selectors.push(selector);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return selectors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter selectors by Media Query.
|
||||
*
|
||||
* @param {Array} selectors to filter
|
||||
* @param {Array} useMqs Array with strings of media queries that should pass (<name> <expression>)
|
||||
* @return {Array} Filtered selectors that match the passed media queries
|
||||
*/
|
||||
function filterByMqs(selectors, useMqs) {
|
||||
return selectors.filter(function (selector) {
|
||||
if (selector.atrule === null) {
|
||||
return ~useMqs.indexOf('');
|
||||
}
|
||||
|
||||
var mqName = selector.atrule.name;
|
||||
var mqStr = mqName;
|
||||
if (
|
||||
selector.atrule.expression &&
|
||||
selector.atrule.expression.children.first().type === 'MediaQueryList'
|
||||
) {
|
||||
var mqExpr = csstree.generate(selector.atrule.expression);
|
||||
mqStr = [mqName, mqExpr].join(' ');
|
||||
}
|
||||
|
||||
return ~useMqs.indexOf(mqStr);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter selectors by the pseudo-elements and/or -classes they contain.
|
||||
*
|
||||
* @param {Array} selectors to filter
|
||||
* @param {Array} usePseudos Array with strings of single or sequence of pseudo-elements and/or -classes that should pass
|
||||
* @return {Array} Filtered selectors that match the passed pseudo-elements and/or -classes
|
||||
*/
|
||||
function filterByPseudos(selectors, usePseudos) {
|
||||
return selectors.filter(function (selector) {
|
||||
var pseudoSelectorsStr = csstree.generate({
|
||||
type: 'Selector',
|
||||
children: new List().fromArray(
|
||||
selector.pseudos.map(function (pseudo) {
|
||||
return pseudo.item.data;
|
||||
})
|
||||
),
|
||||
});
|
||||
return ~usePseudos.indexOf(pseudoSelectorsStr);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove pseudo-elements and/or -classes from the selectors for proper matching.
|
||||
*
|
||||
* @param {Array} selectors to clean
|
||||
* @return {void}
|
||||
*/
|
||||
function cleanPseudos(selectors) {
|
||||
selectors.forEach(function (selector) {
|
||||
selector.pseudos.forEach(function (pseudo) {
|
||||
pseudo.list.remove(pseudo.item);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two selector specificities.
|
||||
* extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
|
||||
*
|
||||
* @param {Array} aSpecificity Specificity of selector A
|
||||
* @param {Array} bSpecificity Specificity of selector B
|
||||
* @return {number} Score of selector specificity A compared to selector specificity B
|
||||
*/
|
||||
function compareSpecificity(aSpecificity, bSpecificity) {
|
||||
for (var i = 0; i < 4; i += 1) {
|
||||
if (aSpecificity[i] < bSpecificity[i]) {
|
||||
return -1;
|
||||
} else if (aSpecificity[i] > bSpecificity[i]) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two simple selectors.
|
||||
*
|
||||
* @param {Object} aSimpleSelectorNode Simple selector A
|
||||
* @param {Object} bSimpleSelectorNode Simple selector B
|
||||
* @return {number} Score of selector A compared to selector B
|
||||
*/
|
||||
function compareSimpleSelectorNode(aSimpleSelectorNode, bSimpleSelectorNode) {
|
||||
var aSpecificity = specificity(aSimpleSelectorNode),
|
||||
bSpecificity = specificity(bSimpleSelectorNode);
|
||||
return compareSpecificity(aSpecificity, bSpecificity);
|
||||
}
|
||||
|
||||
function _bySelectorSpecificity(selectorA, selectorB) {
|
||||
return compareSimpleSelectorNode(selectorA.item.data, selectorB.item.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort selectors stably by their specificity.
|
||||
*
|
||||
* @param {Array} selectors to be sorted
|
||||
* @return {Array} Stable sorted selectors
|
||||
*/
|
||||
function sortSelectors(selectors) {
|
||||
return stable(selectors, _bySelectorSpecificity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a css-tree AST style declaration to CSSStyleDeclaration property.
|
||||
*
|
||||
* @param {import('css-tree').CssNode} declaration css-tree style declaration
|
||||
* @return {Object} CSSStyleDeclaration property
|
||||
*/
|
||||
function csstreeToStyleDeclaration(declaration) {
|
||||
var propertyName = declaration.property,
|
||||
propertyValue = csstree.generate(declaration.value),
|
||||
propertyPriority = declaration.important ? 'important' : '';
|
||||
return {
|
||||
name: propertyName,
|
||||
value: propertyValue,
|
||||
priority: propertyPriority,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the CSS string of a style element
|
||||
*
|
||||
* @param {Object} elem style element
|
||||
* @return {string} CSS string or empty array if no styles are set
|
||||
*/
|
||||
function getCssStr(elem) {
|
||||
if (
|
||||
elem.children.length > 0 &&
|
||||
(elem.children[0].type === 'text' || elem.children[0].type === 'cdata')
|
||||
) {
|
||||
return elem.children[0].value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the CSS string of a style element
|
||||
*
|
||||
* @param {Object} elem style element
|
||||
* @param {string} css string to be set
|
||||
* @return {string} reference to field with CSS
|
||||
*/
|
||||
function setCssStr(elem, css) {
|
||||
if (elem.children.length === 0) {
|
||||
elem.children.push({
|
||||
type: 'text',
|
||||
value: '',
|
||||
});
|
||||
}
|
||||
|
||||
if (elem.children[0].type !== 'text' && elem.children[0].type !== 'cdata') {
|
||||
return css;
|
||||
}
|
||||
|
||||
elem.children[0].value = css;
|
||||
|
||||
return css;
|
||||
}
|
||||
|
||||
module.exports.flattenToSelectors = flattenToSelectors;
|
||||
|
||||
module.exports.filterByMqs = filterByMqs;
|
||||
module.exports.filterByPseudos = filterByPseudos;
|
||||
module.exports.cleanPseudos = cleanPseudos;
|
||||
|
||||
module.exports.compareSpecificity = compareSpecificity;
|
||||
module.exports.compareSimpleSelectorNode = compareSimpleSelectorNode;
|
||||
|
||||
module.exports.sortSelectors = sortSelectors;
|
||||
|
||||
module.exports.csstreeToStyleDeclaration = csstreeToStyleDeclaration;
|
||||
|
||||
module.exports.getCssStr = getCssStr;
|
||||
module.exports.setCssStr = setCssStr;
|
||||
259
node_modules/svgo/lib/parser.js
generated
vendored
Normal file
259
node_modules/svgo/lib/parser.js
generated
vendored
Normal file
@@ -0,0 +1,259 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('./types').XastNode} XastNode
|
||||
* @typedef {import('./types').XastInstruction} XastInstruction
|
||||
* @typedef {import('./types').XastDoctype} XastDoctype
|
||||
* @typedef {import('./types').XastComment} XastComment
|
||||
* @typedef {import('./types').XastRoot} XastRoot
|
||||
* @typedef {import('./types').XastElement} XastElement
|
||||
* @typedef {import('./types').XastCdata} XastCdata
|
||||
* @typedef {import('./types').XastText} XastText
|
||||
* @typedef {import('./types').XastParent} XastParent
|
||||
*/
|
||||
|
||||
// @ts-ignore sax will be replaced with something else later
|
||||
const SAX = require('@trysound/sax');
|
||||
const JSAPI = require('./svgo/jsAPI.js');
|
||||
const { textElems } = require('../plugins/_collections.js');
|
||||
|
||||
class SvgoParserError extends Error {
|
||||
/**
|
||||
* @param message {string}
|
||||
* @param line {number}
|
||||
* @param column {number}
|
||||
* @param source {string}
|
||||
* @param file {void | string}
|
||||
*/
|
||||
constructor(message, line, column, source, file) {
|
||||
super(message);
|
||||
this.name = 'SvgoParserError';
|
||||
this.message = `${file || '<input>'}:${line}:${column}: ${message}`;
|
||||
this.reason = message;
|
||||
this.line = line;
|
||||
this.column = column;
|
||||
this.source = source;
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, SvgoParserError);
|
||||
}
|
||||
}
|
||||
toString() {
|
||||
const lines = this.source.split(/\r?\n/);
|
||||
const startLine = Math.max(this.line - 3, 0);
|
||||
const endLine = Math.min(this.line + 2, lines.length);
|
||||
const lineNumberWidth = String(endLine).length;
|
||||
const startColumn = Math.max(this.column - 54, 0);
|
||||
const endColumn = Math.max(this.column + 20, 80);
|
||||
const code = lines
|
||||
.slice(startLine, endLine)
|
||||
.map((line, index) => {
|
||||
const lineSlice = line.slice(startColumn, endColumn);
|
||||
let ellipsisPrefix = '';
|
||||
let ellipsisSuffix = '';
|
||||
if (startColumn !== 0) {
|
||||
ellipsisPrefix = startColumn > line.length - 1 ? ' ' : '…';
|
||||
}
|
||||
if (endColumn < line.length - 1) {
|
||||
ellipsisSuffix = '…';
|
||||
}
|
||||
const number = startLine + 1 + index;
|
||||
const gutter = ` ${number.toString().padStart(lineNumberWidth)} | `;
|
||||
if (number === this.line) {
|
||||
const gutterSpacing = gutter.replace(/[^|]/g, ' ');
|
||||
const lineSpacing = (
|
||||
ellipsisPrefix + line.slice(startColumn, this.column - 1)
|
||||
).replace(/[^\t]/g, ' ');
|
||||
const spacing = gutterSpacing + lineSpacing;
|
||||
return `>${gutter}${ellipsisPrefix}${lineSlice}${ellipsisSuffix}\n ${spacing}^`;
|
||||
}
|
||||
return ` ${gutter}${ellipsisPrefix}${lineSlice}${ellipsisSuffix}`;
|
||||
})
|
||||
.join('\n');
|
||||
return `${this.name}: ${this.message}\n\n${code}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
const entityDeclaration = /<!ENTITY\s+(\S+)\s+(?:'([^']+)'|"([^"]+)")\s*>/g;
|
||||
|
||||
const config = {
|
||||
strict: true,
|
||||
trim: false,
|
||||
normalize: false,
|
||||
lowercase: true,
|
||||
xmlns: true,
|
||||
position: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert SVG (XML) string to SVG-as-JS object.
|
||||
*
|
||||
* @type {(data: string, from?: string) => XastRoot}
|
||||
*/
|
||||
const parseSvg = (data, from) => {
|
||||
const sax = SAX.parser(config.strict, config);
|
||||
/**
|
||||
* @type {XastRoot}
|
||||
*/
|
||||
const root = new JSAPI({ type: 'root', children: [] });
|
||||
/**
|
||||
* @type {XastParent}
|
||||
*/
|
||||
let current = root;
|
||||
/**
|
||||
* @type {Array<XastParent>}
|
||||
*/
|
||||
const stack = [root];
|
||||
|
||||
/**
|
||||
* @type {<T extends XastNode>(node: T) => T}
|
||||
*/
|
||||
const pushToContent = (node) => {
|
||||
const wrapped = new JSAPI(node, current);
|
||||
current.children.push(wrapped);
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(doctype: string) => void}
|
||||
*/
|
||||
sax.ondoctype = (doctype) => {
|
||||
/**
|
||||
* @type {XastDoctype}
|
||||
*/
|
||||
const node = {
|
||||
type: 'doctype',
|
||||
// TODO parse doctype for name, public and system to match xast
|
||||
name: 'svg',
|
||||
data: {
|
||||
doctype,
|
||||
},
|
||||
};
|
||||
pushToContent(node);
|
||||
const subsetStart = doctype.indexOf('[');
|
||||
if (subsetStart >= 0) {
|
||||
entityDeclaration.lastIndex = subsetStart;
|
||||
let entityMatch = entityDeclaration.exec(data);
|
||||
while (entityMatch != null) {
|
||||
sax.ENTITIES[entityMatch[1]] = entityMatch[2] || entityMatch[3];
|
||||
entityMatch = entityDeclaration.exec(data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(data: { name: string, body: string }) => void}
|
||||
*/
|
||||
sax.onprocessinginstruction = (data) => {
|
||||
/**
|
||||
* @type {XastInstruction}
|
||||
*/
|
||||
const node = {
|
||||
type: 'instruction',
|
||||
name: data.name,
|
||||
value: data.body,
|
||||
};
|
||||
pushToContent(node);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(comment: string) => void}
|
||||
*/
|
||||
sax.oncomment = (comment) => {
|
||||
/**
|
||||
* @type {XastComment}
|
||||
*/
|
||||
const node = {
|
||||
type: 'comment',
|
||||
value: comment.trim(),
|
||||
};
|
||||
pushToContent(node);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(cdata: string) => void}
|
||||
*/
|
||||
sax.oncdata = (cdata) => {
|
||||
/**
|
||||
* @type {XastCdata}
|
||||
*/
|
||||
const node = {
|
||||
type: 'cdata',
|
||||
value: cdata,
|
||||
};
|
||||
pushToContent(node);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(data: { name: string, attributes: Record<string, { value: string }>}) => void}
|
||||
*/
|
||||
sax.onopentag = (data) => {
|
||||
/**
|
||||
* @type {XastElement}
|
||||
*/
|
||||
let element = {
|
||||
type: 'element',
|
||||
name: data.name,
|
||||
attributes: {},
|
||||
children: [],
|
||||
};
|
||||
for (const [name, attr] of Object.entries(data.attributes)) {
|
||||
element.attributes[name] = attr.value;
|
||||
}
|
||||
element = pushToContent(element);
|
||||
current = element;
|
||||
stack.push(element);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(text: string) => void}
|
||||
*/
|
||||
sax.ontext = (text) => {
|
||||
if (current.type === 'element') {
|
||||
// prevent trimming of meaningful whitespace inside textual tags
|
||||
if (textElems.includes(current.name)) {
|
||||
/**
|
||||
* @type {XastText}
|
||||
*/
|
||||
const node = {
|
||||
type: 'text',
|
||||
value: text,
|
||||
};
|
||||
pushToContent(node);
|
||||
} else if (/\S/.test(text)) {
|
||||
/**
|
||||
* @type {XastText}
|
||||
*/
|
||||
const node = {
|
||||
type: 'text',
|
||||
value: text.trim(),
|
||||
};
|
||||
pushToContent(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
sax.onclosetag = () => {
|
||||
stack.pop();
|
||||
current = stack[stack.length - 1];
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(e: any) => void}
|
||||
*/
|
||||
sax.onerror = (e) => {
|
||||
const error = new SvgoParserError(
|
||||
e.reason,
|
||||
e.line + 1,
|
||||
e.column,
|
||||
data,
|
||||
from
|
||||
);
|
||||
if (e.message.indexOf('Unexpected end') === -1) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
sax.write(data).close();
|
||||
return root;
|
||||
};
|
||||
exports.parseSvg = parseSvg;
|
||||
347
node_modules/svgo/lib/path.js
generated
vendored
Normal file
347
node_modules/svgo/lib/path.js
generated
vendored
Normal file
@@ -0,0 +1,347 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('./types').PathDataItem} PathDataItem
|
||||
* @typedef {import('./types').PathDataCommand} PathDataCommand
|
||||
*/
|
||||
|
||||
// Based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF
|
||||
|
||||
const argsCountPerCommand = {
|
||||
M: 2,
|
||||
m: 2,
|
||||
Z: 0,
|
||||
z: 0,
|
||||
L: 2,
|
||||
l: 2,
|
||||
H: 1,
|
||||
h: 1,
|
||||
V: 1,
|
||||
v: 1,
|
||||
C: 6,
|
||||
c: 6,
|
||||
S: 4,
|
||||
s: 4,
|
||||
Q: 4,
|
||||
q: 4,
|
||||
T: 2,
|
||||
t: 2,
|
||||
A: 7,
|
||||
a: 7,
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(c: string) => c is PathDataCommand}
|
||||
*/
|
||||
const isCommand = (c) => {
|
||||
return c in argsCountPerCommand;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(c: string) => boolean}
|
||||
*/
|
||||
const isWsp = (c) => {
|
||||
const codePoint = c.codePointAt(0);
|
||||
return (
|
||||
codePoint === 0x20 ||
|
||||
codePoint === 0x9 ||
|
||||
codePoint === 0xd ||
|
||||
codePoint === 0xa
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(c: string) => boolean}
|
||||
*/
|
||||
const isDigit = (c) => {
|
||||
const codePoint = c.codePointAt(0);
|
||||
if (codePoint == null) {
|
||||
return false;
|
||||
}
|
||||
return 48 <= codePoint && codePoint <= 57;
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {'none' | 'sign' | 'whole' | 'decimal_point' | 'decimal' | 'e' | 'exponent_sign' | 'exponent'} ReadNumberState
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {(string: string, cursor: number) => [number, number | null]}
|
||||
*/
|
||||
const readNumber = (string, cursor) => {
|
||||
let i = cursor;
|
||||
let value = '';
|
||||
let state = /** @type {ReadNumberState} */ ('none');
|
||||
for (; i < string.length; i += 1) {
|
||||
const c = string[i];
|
||||
if (c === '+' || c === '-') {
|
||||
if (state === 'none') {
|
||||
state = 'sign';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
if (state === 'e') {
|
||||
state = 'exponent_sign';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isDigit(c)) {
|
||||
if (state === 'none' || state === 'sign' || state === 'whole') {
|
||||
state = 'whole';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
if (state === 'decimal_point' || state === 'decimal') {
|
||||
state = 'decimal';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
if (state === 'e' || state === 'exponent_sign' || state === 'exponent') {
|
||||
state = 'exponent';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (c === '.') {
|
||||
if (state === 'none' || state === 'sign' || state === 'whole') {
|
||||
state = 'decimal_point';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (c === 'E' || c == 'e') {
|
||||
if (
|
||||
state === 'whole' ||
|
||||
state === 'decimal_point' ||
|
||||
state === 'decimal'
|
||||
) {
|
||||
state = 'e';
|
||||
value += c;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
const number = Number.parseFloat(value);
|
||||
if (Number.isNaN(number)) {
|
||||
return [cursor, null];
|
||||
} else {
|
||||
// step back to delegate iteration to parent loop
|
||||
return [i - 1, number];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(string: string) => Array<PathDataItem>}
|
||||
*/
|
||||
const parsePathData = (string) => {
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [];
|
||||
/**
|
||||
* @type {null | PathDataCommand}
|
||||
*/
|
||||
let command = null;
|
||||
let args = /** @type {number[]} */ ([]);
|
||||
let argsCount = 0;
|
||||
let canHaveComma = false;
|
||||
let hadComma = false;
|
||||
for (let i = 0; i < string.length; i += 1) {
|
||||
const c = string.charAt(i);
|
||||
if (isWsp(c)) {
|
||||
continue;
|
||||
}
|
||||
// allow comma only between arguments
|
||||
if (canHaveComma && c === ',') {
|
||||
if (hadComma) {
|
||||
break;
|
||||
}
|
||||
hadComma = true;
|
||||
continue;
|
||||
}
|
||||
if (isCommand(c)) {
|
||||
if (hadComma) {
|
||||
return pathData;
|
||||
}
|
||||
if (command == null) {
|
||||
// moveto should be leading command
|
||||
if (c !== 'M' && c !== 'm') {
|
||||
return pathData;
|
||||
}
|
||||
} else {
|
||||
// stop if previous command arguments are not flushed
|
||||
if (args.length !== 0) {
|
||||
return pathData;
|
||||
}
|
||||
}
|
||||
command = c;
|
||||
args = [];
|
||||
argsCount = argsCountPerCommand[command];
|
||||
canHaveComma = false;
|
||||
// flush command without arguments
|
||||
if (argsCount === 0) {
|
||||
pathData.push({ command, args });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// avoid parsing arguments if no command detected
|
||||
if (command == null) {
|
||||
return pathData;
|
||||
}
|
||||
// read next argument
|
||||
let newCursor = i;
|
||||
let number = null;
|
||||
if (command === 'A' || command === 'a') {
|
||||
const position = args.length;
|
||||
if (position === 0 || position === 1) {
|
||||
// allow only positive number without sign as first two arguments
|
||||
if (c !== '+' && c !== '-') {
|
||||
[newCursor, number] = readNumber(string, i);
|
||||
}
|
||||
}
|
||||
if (position === 2 || position === 5 || position === 6) {
|
||||
[newCursor, number] = readNumber(string, i);
|
||||
}
|
||||
if (position === 3 || position === 4) {
|
||||
// read flags
|
||||
if (c === '0') {
|
||||
number = 0;
|
||||
}
|
||||
if (c === '1') {
|
||||
number = 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
[newCursor, number] = readNumber(string, i);
|
||||
}
|
||||
if (number == null) {
|
||||
return pathData;
|
||||
}
|
||||
args.push(number);
|
||||
canHaveComma = true;
|
||||
hadComma = false;
|
||||
i = newCursor;
|
||||
// flush arguments when necessary count is reached
|
||||
if (args.length === argsCount) {
|
||||
pathData.push({ command, args });
|
||||
// subsequent moveto coordinates are threated as implicit lineto commands
|
||||
if (command === 'M') {
|
||||
command = 'L';
|
||||
}
|
||||
if (command === 'm') {
|
||||
command = 'l';
|
||||
}
|
||||
args = [];
|
||||
}
|
||||
}
|
||||
return pathData;
|
||||
};
|
||||
exports.parsePathData = parsePathData;
|
||||
|
||||
/**
|
||||
* @type {(number: number, precision?: number) => string}
|
||||
*/
|
||||
const stringifyNumber = (number, precision) => {
|
||||
if (precision != null) {
|
||||
const ratio = 10 ** precision;
|
||||
number = Math.round(number * ratio) / ratio;
|
||||
}
|
||||
// remove zero whole from decimal number
|
||||
return number.toString().replace(/^0\./, '.').replace(/^-0\./, '-.');
|
||||
};
|
||||
|
||||
/**
|
||||
* Elliptical arc large-arc and sweep flags are rendered with spaces
|
||||
* because many non-browser environments are not able to parse such paths
|
||||
*
|
||||
* @type {(
|
||||
* command: string,
|
||||
* args: number[],
|
||||
* precision?: number,
|
||||
* disableSpaceAfterFlags?: boolean
|
||||
* ) => string}
|
||||
*/
|
||||
const stringifyArgs = (command, args, precision, disableSpaceAfterFlags) => {
|
||||
let result = '';
|
||||
let prev = '';
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
const number = args[i];
|
||||
const numberString = stringifyNumber(number, precision);
|
||||
if (
|
||||
disableSpaceAfterFlags &&
|
||||
(command === 'A' || command === 'a') &&
|
||||
// consider combined arcs
|
||||
(i % 7 === 4 || i % 7 === 5)
|
||||
) {
|
||||
result += numberString;
|
||||
} else if (i === 0 || numberString.startsWith('-')) {
|
||||
// avoid space before first and negative numbers
|
||||
result += numberString;
|
||||
} else if (prev.includes('.') && numberString.startsWith('.')) {
|
||||
// remove space before decimal with zero whole
|
||||
// only when previous number is also decimal
|
||||
result += numberString;
|
||||
} else {
|
||||
result += ` ${numberString}`;
|
||||
}
|
||||
prev = numberString;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* pathData: Array<PathDataItem>;
|
||||
* precision?: number;
|
||||
* disableSpaceAfterFlags?: boolean;
|
||||
* }} StringifyPathDataOptions
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {(options: StringifyPathDataOptions) => string}
|
||||
*/
|
||||
const stringifyPathData = ({ pathData, precision, disableSpaceAfterFlags }) => {
|
||||
// combine sequence of the same commands
|
||||
let combined = [];
|
||||
for (let i = 0; i < pathData.length; i += 1) {
|
||||
const { command, args } = pathData[i];
|
||||
if (i === 0) {
|
||||
combined.push({ command, args });
|
||||
} else {
|
||||
/**
|
||||
* @type {PathDataItem}
|
||||
*/
|
||||
const last = combined[combined.length - 1];
|
||||
// match leading moveto with following lineto
|
||||
if (i === 1) {
|
||||
if (command === 'L') {
|
||||
last.command = 'M';
|
||||
}
|
||||
if (command === 'l') {
|
||||
last.command = 'm';
|
||||
}
|
||||
}
|
||||
if (
|
||||
(last.command === command &&
|
||||
last.command !== 'M' &&
|
||||
last.command !== 'm') ||
|
||||
// combine matching moveto and lineto sequences
|
||||
(last.command === 'M' && command === 'L') ||
|
||||
(last.command === 'm' && command === 'l')
|
||||
) {
|
||||
last.args = [...last.args, ...args];
|
||||
} else {
|
||||
combined.push({ command, args });
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = '';
|
||||
for (const { command, args } of combined) {
|
||||
result +=
|
||||
command + stringifyArgs(command, args, precision, disableSpaceAfterFlags);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
exports.stringifyPathData = stringifyPathData;
|
||||
326
node_modules/svgo/lib/stringifier.js
generated
vendored
Normal file
326
node_modules/svgo/lib/stringifier.js
generated
vendored
Normal file
@@ -0,0 +1,326 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('./types').XastParent} XastParent
|
||||
* @typedef {import('./types').XastRoot} XastRoot
|
||||
* @typedef {import('./types').XastElement} XastElement
|
||||
* @typedef {import('./types').XastInstruction} XastInstruction
|
||||
* @typedef {import('./types').XastDoctype} XastDoctype
|
||||
* @typedef {import('./types').XastText} XastText
|
||||
* @typedef {import('./types').XastCdata} XastCdata
|
||||
* @typedef {import('./types').XastComment} XastComment
|
||||
* @typedef {import('./types').StringifyOptions} StringifyOptions
|
||||
*/
|
||||
|
||||
const { textElems } = require('../plugins/_collections.js');
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* width: void | string,
|
||||
* height: void | string,
|
||||
* indent: string,
|
||||
* textContext: null | XastElement,
|
||||
* indentLevel: number,
|
||||
* }} State
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Required<StringifyOptions>} Options
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {(char: string) => string}
|
||||
*/
|
||||
const encodeEntity = (char) => {
|
||||
return entities[char];
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Options}
|
||||
*/
|
||||
const defaults = {
|
||||
doctypeStart: '<!DOCTYPE',
|
||||
doctypeEnd: '>',
|
||||
procInstStart: '<?',
|
||||
procInstEnd: '?>',
|
||||
tagOpenStart: '<',
|
||||
tagOpenEnd: '>',
|
||||
tagCloseStart: '</',
|
||||
tagCloseEnd: '>',
|
||||
tagShortStart: '<',
|
||||
tagShortEnd: '/>',
|
||||
attrStart: '="',
|
||||
attrEnd: '"',
|
||||
commentStart: '<!--',
|
||||
commentEnd: '-->',
|
||||
cdataStart: '<![CDATA[',
|
||||
cdataEnd: ']]>',
|
||||
textStart: '',
|
||||
textEnd: '',
|
||||
indent: 4,
|
||||
regEntities: /[&'"<>]/g,
|
||||
regValEntities: /[&"<>]/g,
|
||||
encodeEntity: encodeEntity,
|
||||
pretty: false,
|
||||
useShortTags: true,
|
||||
eol: 'lf',
|
||||
finalNewline: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Record<string, string>}
|
||||
*/
|
||||
const entities = {
|
||||
'&': '&',
|
||||
"'": ''',
|
||||
'"': '"',
|
||||
'>': '>',
|
||||
'<': '<',
|
||||
};
|
||||
|
||||
/**
|
||||
* convert XAST to SVG string
|
||||
*
|
||||
* @type {(data: XastRoot, config: StringifyOptions) => {
|
||||
* data: string,
|
||||
* info: {
|
||||
* width: void | string,
|
||||
* height: void | string
|
||||
* }
|
||||
* }}
|
||||
*/
|
||||
const stringifySvg = (data, userOptions = {}) => {
|
||||
/**
|
||||
* @type {Options}
|
||||
*/
|
||||
const config = { ...defaults, ...userOptions };
|
||||
const indent = config.indent;
|
||||
let newIndent = ' ';
|
||||
if (typeof indent === 'number' && Number.isNaN(indent) === false) {
|
||||
newIndent = indent < 0 ? '\t' : ' '.repeat(indent);
|
||||
} else if (typeof indent === 'string') {
|
||||
newIndent = indent;
|
||||
}
|
||||
/**
|
||||
* @type {State}
|
||||
*/
|
||||
const state = {
|
||||
// TODO remove width and height in v3
|
||||
width: undefined,
|
||||
height: undefined,
|
||||
indent: newIndent,
|
||||
textContext: null,
|
||||
indentLevel: 0,
|
||||
};
|
||||
const eol = config.eol === 'crlf' ? '\r\n' : '\n';
|
||||
if (config.pretty) {
|
||||
config.doctypeEnd += eol;
|
||||
config.procInstEnd += eol;
|
||||
config.commentEnd += eol;
|
||||
config.cdataEnd += eol;
|
||||
config.tagShortEnd += eol;
|
||||
config.tagOpenEnd += eol;
|
||||
config.tagCloseEnd += eol;
|
||||
config.textEnd += eol;
|
||||
}
|
||||
let svg = stringifyNode(data, config, state);
|
||||
if (config.finalNewline && svg.length > 0 && svg[svg.length - 1] !== '\n') {
|
||||
svg += eol;
|
||||
}
|
||||
return {
|
||||
data: svg,
|
||||
info: {
|
||||
width: state.width,
|
||||
height: state.height,
|
||||
},
|
||||
};
|
||||
};
|
||||
exports.stringifySvg = stringifySvg;
|
||||
|
||||
/**
|
||||
* @type {(node: XastParent, config: Options, state: State) => string}
|
||||
*/
|
||||
const stringifyNode = (data, config, state) => {
|
||||
let svg = '';
|
||||
state.indentLevel += 1;
|
||||
for (const item of data.children) {
|
||||
if (item.type === 'element') {
|
||||
svg += stringifyElement(item, config, state);
|
||||
}
|
||||
if (item.type === 'text') {
|
||||
svg += stringifyText(item, config, state);
|
||||
}
|
||||
if (item.type === 'doctype') {
|
||||
svg += stringifyDoctype(item, config);
|
||||
}
|
||||
if (item.type === 'instruction') {
|
||||
svg += stringifyInstruction(item, config);
|
||||
}
|
||||
if (item.type === 'comment') {
|
||||
svg += stringifyComment(item, config);
|
||||
}
|
||||
if (item.type === 'cdata') {
|
||||
svg += stringifyCdata(item, config, state);
|
||||
}
|
||||
}
|
||||
state.indentLevel -= 1;
|
||||
return svg;
|
||||
};
|
||||
|
||||
/**
|
||||
* create indent string in accordance with the current node level.
|
||||
*
|
||||
* @type {(config: Options, state: State) => string}
|
||||
*/
|
||||
const createIndent = (config, state) => {
|
||||
let indent = '';
|
||||
if (config.pretty && state.textContext == null) {
|
||||
indent = state.indent.repeat(state.indentLevel - 1);
|
||||
}
|
||||
return indent;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastDoctype, config: Options) => string}
|
||||
*/
|
||||
const stringifyDoctype = (node, config) => {
|
||||
return config.doctypeStart + node.data.doctype + config.doctypeEnd;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastInstruction, config: Options) => string}
|
||||
*/
|
||||
const stringifyInstruction = (node, config) => {
|
||||
return (
|
||||
config.procInstStart + node.name + ' ' + node.value + config.procInstEnd
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastComment, config: Options) => string}
|
||||
*/
|
||||
const stringifyComment = (node, config) => {
|
||||
return config.commentStart + node.value + config.commentEnd;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastCdata, config: Options, state: State) => string}
|
||||
*/
|
||||
const stringifyCdata = (node, config, state) => {
|
||||
return (
|
||||
createIndent(config, state) +
|
||||
config.cdataStart +
|
||||
node.value +
|
||||
config.cdataEnd
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastElement, config: Options, state: State) => string}
|
||||
*/
|
||||
const stringifyElement = (node, config, state) => {
|
||||
// beautiful injection for obtaining SVG information :)
|
||||
if (
|
||||
node.name === 'svg' &&
|
||||
node.attributes.width != null &&
|
||||
node.attributes.height != null
|
||||
) {
|
||||
state.width = node.attributes.width;
|
||||
state.height = node.attributes.height;
|
||||
}
|
||||
|
||||
// empty element and short tag
|
||||
if (node.children.length === 0) {
|
||||
if (config.useShortTags) {
|
||||
return (
|
||||
createIndent(config, state) +
|
||||
config.tagShortStart +
|
||||
node.name +
|
||||
stringifyAttributes(node, config) +
|
||||
config.tagShortEnd
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
createIndent(config, state) +
|
||||
config.tagShortStart +
|
||||
node.name +
|
||||
stringifyAttributes(node, config) +
|
||||
config.tagOpenEnd +
|
||||
config.tagCloseStart +
|
||||
node.name +
|
||||
config.tagCloseEnd
|
||||
);
|
||||
}
|
||||
// non-empty element
|
||||
} else {
|
||||
let tagOpenStart = config.tagOpenStart;
|
||||
let tagOpenEnd = config.tagOpenEnd;
|
||||
let tagCloseStart = config.tagCloseStart;
|
||||
let tagCloseEnd = config.tagCloseEnd;
|
||||
let openIndent = createIndent(config, state);
|
||||
let closeIndent = createIndent(config, state);
|
||||
|
||||
if (state.textContext) {
|
||||
tagOpenStart = defaults.tagOpenStart;
|
||||
tagOpenEnd = defaults.tagOpenEnd;
|
||||
tagCloseStart = defaults.tagCloseStart;
|
||||
tagCloseEnd = defaults.tagCloseEnd;
|
||||
openIndent = '';
|
||||
} else if (textElems.includes(node.name)) {
|
||||
tagOpenEnd = defaults.tagOpenEnd;
|
||||
tagCloseStart = defaults.tagCloseStart;
|
||||
closeIndent = '';
|
||||
state.textContext = node;
|
||||
}
|
||||
|
||||
const children = stringifyNode(node, config, state);
|
||||
|
||||
if (state.textContext === node) {
|
||||
state.textContext = null;
|
||||
}
|
||||
|
||||
return (
|
||||
openIndent +
|
||||
tagOpenStart +
|
||||
node.name +
|
||||
stringifyAttributes(node, config) +
|
||||
tagOpenEnd +
|
||||
children +
|
||||
closeIndent +
|
||||
tagCloseStart +
|
||||
node.name +
|
||||
tagCloseEnd
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastElement, config: Options) => string}
|
||||
*/
|
||||
const stringifyAttributes = (node, config) => {
|
||||
let attrs = '';
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
// TODO remove attributes without values support in v3
|
||||
if (value !== undefined) {
|
||||
const encodedValue = value
|
||||
.toString()
|
||||
.replace(config.regValEntities, config.encodeEntity);
|
||||
attrs += ' ' + name + config.attrStart + encodedValue + config.attrEnd;
|
||||
} else {
|
||||
attrs += ' ' + name;
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastText, config: Options, state: State) => string}
|
||||
*/
|
||||
const stringifyText = (node, config, state) => {
|
||||
return (
|
||||
createIndent(config, state) +
|
||||
config.textStart +
|
||||
node.value.replace(config.regEntities, config.encodeEntity) +
|
||||
(state.textContext ? '' : config.textEnd)
|
||||
);
|
||||
};
|
||||
283
node_modules/svgo/lib/style.js
generated
vendored
Normal file
283
node_modules/svgo/lib/style.js
generated
vendored
Normal file
@@ -0,0 +1,283 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('css-tree').Rule} CsstreeRule
|
||||
* @typedef {import('./types').Specificity} Specificity
|
||||
* @typedef {import('./types').Stylesheet} Stylesheet
|
||||
* @typedef {import('./types').StylesheetRule} StylesheetRule
|
||||
* @typedef {import('./types').StylesheetDeclaration} StylesheetDeclaration
|
||||
* @typedef {import('./types').ComputedStyles} ComputedStyles
|
||||
* @typedef {import('./types').XastRoot} XastRoot
|
||||
* @typedef {import('./types').XastElement} XastElement
|
||||
* @typedef {import('./types').XastParent} XastParent
|
||||
* @typedef {import('./types').XastChild} XastChild
|
||||
*/
|
||||
|
||||
const stable = require('stable');
|
||||
const csstree = require('css-tree');
|
||||
// @ts-ignore not defined in @types/csso
|
||||
const specificity = require('csso/lib/restructure/prepare/specificity');
|
||||
const { visit, matches } = require('./xast.js');
|
||||
const {
|
||||
attrsGroups,
|
||||
inheritableAttrs,
|
||||
presentationNonInheritableGroupAttrs,
|
||||
} = require('../plugins/_collections.js');
|
||||
|
||||
// @ts-ignore not defined in @types/csstree
|
||||
const csstreeWalkSkip = csstree.walk.skip;
|
||||
|
||||
/**
|
||||
* @type {(ruleNode: CsstreeRule, dynamic: boolean) => StylesheetRule}
|
||||
*/
|
||||
const parseRule = (ruleNode, dynamic) => {
|
||||
let selectors;
|
||||
let selectorsSpecificity;
|
||||
/**
|
||||
* @type {Array<StylesheetDeclaration>}
|
||||
*/
|
||||
const declarations = [];
|
||||
csstree.walk(ruleNode, (cssNode) => {
|
||||
if (cssNode.type === 'SelectorList') {
|
||||
// compute specificity from original node to consider pseudo classes
|
||||
selectorsSpecificity = specificity(cssNode);
|
||||
const newSelectorsNode = csstree.clone(cssNode);
|
||||
csstree.walk(newSelectorsNode, (pseudoClassNode, item, list) => {
|
||||
if (pseudoClassNode.type === 'PseudoClassSelector') {
|
||||
dynamic = true;
|
||||
list.remove(item);
|
||||
}
|
||||
});
|
||||
selectors = csstree.generate(newSelectorsNode);
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
if (cssNode.type === 'Declaration') {
|
||||
declarations.push({
|
||||
name: cssNode.property,
|
||||
value: csstree.generate(cssNode.value),
|
||||
important: cssNode.important === true,
|
||||
});
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
});
|
||||
if (selectors == null || selectorsSpecificity == null) {
|
||||
throw Error('assert');
|
||||
}
|
||||
return {
|
||||
dynamic,
|
||||
selectors,
|
||||
specificity: selectorsSpecificity,
|
||||
declarations,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(css: string, dynamic: boolean) => Array<StylesheetRule>}
|
||||
*/
|
||||
const parseStylesheet = (css, dynamic) => {
|
||||
/**
|
||||
* @type {Array<StylesheetRule>}
|
||||
*/
|
||||
const rules = [];
|
||||
const ast = csstree.parse(css, {
|
||||
parseValue: false,
|
||||
parseAtrulePrelude: false,
|
||||
});
|
||||
csstree.walk(ast, (cssNode) => {
|
||||
if (cssNode.type === 'Rule') {
|
||||
rules.push(parseRule(cssNode, dynamic || false));
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
if (cssNode.type === 'Atrule') {
|
||||
if (cssNode.name === 'keyframes') {
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
csstree.walk(cssNode, (ruleNode) => {
|
||||
if (ruleNode.type === 'Rule') {
|
||||
rules.push(parseRule(ruleNode, dynamic || true));
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
});
|
||||
return csstreeWalkSkip;
|
||||
}
|
||||
});
|
||||
return rules;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(css: string) => Array<StylesheetDeclaration>}
|
||||
*/
|
||||
const parseStyleDeclarations = (css) => {
|
||||
/**
|
||||
* @type {Array<StylesheetDeclaration>}
|
||||
*/
|
||||
const declarations = [];
|
||||
const ast = csstree.parse(css, {
|
||||
context: 'declarationList',
|
||||
parseValue: false,
|
||||
});
|
||||
csstree.walk(ast, (cssNode) => {
|
||||
if (cssNode.type === 'Declaration') {
|
||||
declarations.push({
|
||||
name: cssNode.property,
|
||||
value: csstree.generate(cssNode.value),
|
||||
important: cssNode.important === true,
|
||||
});
|
||||
}
|
||||
});
|
||||
return declarations;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
|
||||
*/
|
||||
const computeOwnStyle = (stylesheet, node) => {
|
||||
/**
|
||||
* @type {ComputedStyles}
|
||||
*/
|
||||
const computedStyle = {};
|
||||
const importantStyles = new Map();
|
||||
|
||||
// collect attributes
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (attrsGroups.presentation.includes(name)) {
|
||||
computedStyle[name] = { type: 'static', inherited: false, value };
|
||||
importantStyles.set(name, false);
|
||||
}
|
||||
}
|
||||
|
||||
// collect matching rules
|
||||
for (const { selectors, declarations, dynamic } of stylesheet.rules) {
|
||||
if (matches(node, selectors)) {
|
||||
for (const { name, value, important } of declarations) {
|
||||
const computed = computedStyle[name];
|
||||
if (computed && computed.type === 'dynamic') {
|
||||
continue;
|
||||
}
|
||||
if (dynamic) {
|
||||
computedStyle[name] = { type: 'dynamic', inherited: false };
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
computed == null ||
|
||||
important === true ||
|
||||
importantStyles.get(name) === false
|
||||
) {
|
||||
computedStyle[name] = { type: 'static', inherited: false, value };
|
||||
importantStyles.set(name, important);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collect inline styles
|
||||
const styleDeclarations =
|
||||
node.attributes.style == null
|
||||
? []
|
||||
: parseStyleDeclarations(node.attributes.style);
|
||||
for (const { name, value, important } of styleDeclarations) {
|
||||
const computed = computedStyle[name];
|
||||
if (computed && computed.type === 'dynamic') {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
computed == null ||
|
||||
important === true ||
|
||||
importantStyles.get(name) === false
|
||||
) {
|
||||
computedStyle[name] = { type: 'static', inherited: false, value };
|
||||
importantStyles.set(name, important);
|
||||
}
|
||||
}
|
||||
|
||||
return computedStyle;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares two selector specificities.
|
||||
* extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
|
||||
*
|
||||
* @type {(a: Specificity, b: Specificity) => number}
|
||||
*/
|
||||
const compareSpecificity = (a, b) => {
|
||||
for (var i = 0; i < 4; i += 1) {
|
||||
if (a[i] < b[i]) {
|
||||
return -1;
|
||||
} else if (a[i] > b[i]) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(root: XastRoot) => Stylesheet}
|
||||
*/
|
||||
const collectStylesheet = (root) => {
|
||||
/**
|
||||
* @type {Array<StylesheetRule>}
|
||||
*/
|
||||
const rules = [];
|
||||
/**
|
||||
* @type {Map<XastElement, XastParent>}
|
||||
*/
|
||||
const parents = new Map();
|
||||
visit(root, {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// store parents
|
||||
parents.set(node, parentNode);
|
||||
// find and parse all styles
|
||||
if (node.name === 'style') {
|
||||
const dynamic =
|
||||
node.attributes.media != null && node.attributes.media !== 'all';
|
||||
if (
|
||||
node.attributes.type == null ||
|
||||
node.attributes.type === '' ||
|
||||
node.attributes.type === 'text/css'
|
||||
) {
|
||||
const children = node.children;
|
||||
for (const child of children) {
|
||||
if (child.type === 'text' || child.type === 'cdata') {
|
||||
rules.push(...parseStylesheet(child.value, dynamic));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
// sort by selectors specificity
|
||||
stable.inplace(rules, (a, b) =>
|
||||
compareSpecificity(a.specificity, b.specificity)
|
||||
);
|
||||
return { rules, parents };
|
||||
};
|
||||
exports.collectStylesheet = collectStylesheet;
|
||||
|
||||
/**
|
||||
* @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
|
||||
*/
|
||||
const computeStyle = (stylesheet, node) => {
|
||||
const { parents } = stylesheet;
|
||||
// collect inherited styles
|
||||
const computedStyles = computeOwnStyle(stylesheet, node);
|
||||
let parent = parents.get(node);
|
||||
while (parent != null && parent.type !== 'root') {
|
||||
const inheritedStyles = computeOwnStyle(stylesheet, parent);
|
||||
for (const [name, computed] of Object.entries(inheritedStyles)) {
|
||||
if (
|
||||
computedStyles[name] == null &&
|
||||
// ignore not inheritable styles
|
||||
inheritableAttrs.includes(name) === true &&
|
||||
presentationNonInheritableGroupAttrs.includes(name) === false
|
||||
) {
|
||||
computedStyles[name] = { ...computed, inherited: true };
|
||||
}
|
||||
}
|
||||
parent = parents.get(parent);
|
||||
}
|
||||
return computedStyles;
|
||||
};
|
||||
exports.computeStyle = computeStyle;
|
||||
106
node_modules/svgo/lib/svgo-node.js
generated
vendored
Normal file
106
node_modules/svgo/lib/svgo-node.js
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
const { pathToFileURL } = require('url');
|
||||
const path = require('path');
|
||||
const {
|
||||
extendDefaultPlugins,
|
||||
optimize: optimizeAgnostic,
|
||||
createContentItem,
|
||||
} = require('./svgo.js');
|
||||
|
||||
exports.extendDefaultPlugins = extendDefaultPlugins;
|
||||
exports.createContentItem = createContentItem;
|
||||
|
||||
const importConfig = async (configFile) => {
|
||||
let config;
|
||||
// at the moment dynamic import may randomly fail with segfault
|
||||
// to workaround this for some users .cjs extension is loaded
|
||||
// exclusively with require
|
||||
if (configFile.endsWith('.cjs')) {
|
||||
config = require(configFile);
|
||||
} else {
|
||||
try {
|
||||
// dynamic import expects file url instead of path and may fail
|
||||
// when windows path is provided
|
||||
const { default: imported } = await import(pathToFileURL(configFile));
|
||||
config = imported;
|
||||
} catch (importError) {
|
||||
// TODO remove require in v3
|
||||
try {
|
||||
config = require(configFile);
|
||||
} catch (requireError) {
|
||||
// throw original error if es module is detected
|
||||
if (requireError.code === 'ERR_REQUIRE_ESM') {
|
||||
throw importError;
|
||||
} else {
|
||||
throw requireError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (config == null || typeof config !== 'object' || Array.isArray(config)) {
|
||||
throw Error(`Invalid config file "${configFile}"`);
|
||||
}
|
||||
return config;
|
||||
};
|
||||
|
||||
const isFile = async (file) => {
|
||||
try {
|
||||
const stats = await fs.promises.stat(file);
|
||||
return stats.isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadConfig = async (configFile, cwd = process.cwd()) => {
|
||||
if (configFile != null) {
|
||||
if (path.isAbsolute(configFile)) {
|
||||
return await importConfig(configFile);
|
||||
} else {
|
||||
return await importConfig(path.join(cwd, configFile));
|
||||
}
|
||||
}
|
||||
let dir = cwd;
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
const js = path.join(dir, 'svgo.config.js');
|
||||
if (await isFile(js)) {
|
||||
return await importConfig(js);
|
||||
}
|
||||
const mjs = path.join(dir, 'svgo.config.mjs');
|
||||
if (await isFile(mjs)) {
|
||||
return await importConfig(mjs);
|
||||
}
|
||||
const cjs = path.join(dir, 'svgo.config.cjs');
|
||||
if (await isFile(cjs)) {
|
||||
return await importConfig(cjs);
|
||||
}
|
||||
const parent = path.dirname(dir);
|
||||
if (dir === parent) {
|
||||
return null;
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
};
|
||||
exports.loadConfig = loadConfig;
|
||||
|
||||
const optimize = (input, config) => {
|
||||
if (config == null) {
|
||||
config = {};
|
||||
}
|
||||
if (typeof config !== 'object') {
|
||||
throw Error('Config should be an object');
|
||||
}
|
||||
return optimizeAgnostic(input, {
|
||||
...config,
|
||||
js2svg: {
|
||||
// platform specific default for end of line
|
||||
eol: os.EOL === '\r\n' ? 'crlf' : 'lf',
|
||||
...config.js2svg,
|
||||
},
|
||||
});
|
||||
};
|
||||
exports.optimize = optimize;
|
||||
139
node_modules/svgo/lib/svgo.js
generated
vendored
139
node_modules/svgo/lib/svgo.js
generated
vendored
@@ -1,80 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* SVGO is a Nodejs-based tool for optimizing SVG vector graphics files.
|
||||
*
|
||||
* @see https://github.com/svg/svgo
|
||||
*
|
||||
* @author Kir Belevich <kir@soulshine.in> (https://github.com/deepsweet)
|
||||
* @copyright © 2012 Kir Belevich
|
||||
* @license MIT https://raw.githubusercontent.com/svg/svgo/master/LICENSE
|
||||
*/
|
||||
const {
|
||||
defaultPlugins,
|
||||
resolvePluginConfig,
|
||||
extendDefaultPlugins,
|
||||
} = require('./svgo/config.js');
|
||||
const { parseSvg } = require('./parser.js');
|
||||
const { stringifySvg } = require('./stringifier.js');
|
||||
const { invokePlugins } = require('./svgo/plugins.js');
|
||||
const JSAPI = require('./svgo/jsAPI.js');
|
||||
const { encodeSVGDatauri } = require('./svgo/tools.js');
|
||||
|
||||
var CONFIG = require('./svgo/config.js'),
|
||||
SVG2JS = require('./svgo/svg2js.js'),
|
||||
PLUGINS = require('./svgo/plugins.js'),
|
||||
JSAPI = require('./svgo/jsAPI.js'),
|
||||
JS2SVG = require('./svgo/js2svg.js');
|
||||
|
||||
var SVGO = module.exports = function(config) {
|
||||
|
||||
this.config = CONFIG(config);
|
||||
exports.extendDefaultPlugins = extendDefaultPlugins;
|
||||
|
||||
const optimize = (input, config) => {
|
||||
if (config == null) {
|
||||
config = {};
|
||||
}
|
||||
if (typeof config !== 'object') {
|
||||
throw Error('Config should be an object');
|
||||
}
|
||||
const maxPassCount = config.multipass ? 10 : 1;
|
||||
let prevResultSize = Number.POSITIVE_INFINITY;
|
||||
let svgjs = null;
|
||||
const info = {};
|
||||
if (config.path != null) {
|
||||
info.path = config.path;
|
||||
}
|
||||
for (let i = 0; i < maxPassCount; i += 1) {
|
||||
info.multipassCount = i;
|
||||
// TODO throw this error in v3
|
||||
try {
|
||||
svgjs = parseSvg(input, config.path);
|
||||
} catch (error) {
|
||||
return { error: error.toString(), modernError: error };
|
||||
}
|
||||
if (svgjs.error != null) {
|
||||
if (config.path != null) {
|
||||
svgjs.path = config.path;
|
||||
}
|
||||
return svgjs;
|
||||
}
|
||||
const plugins = config.plugins || defaultPlugins;
|
||||
if (Array.isArray(plugins) === false) {
|
||||
throw Error(
|
||||
"Invalid plugins list. Provided 'plugins' in config should be an array."
|
||||
);
|
||||
}
|
||||
const resolvedPlugins = plugins.map(resolvePluginConfig);
|
||||
const globalOverrides = {};
|
||||
if (config.floatPrecision != null) {
|
||||
globalOverrides.floatPrecision = config.floatPrecision;
|
||||
}
|
||||
svgjs = invokePlugins(svgjs, info, resolvedPlugins, null, globalOverrides);
|
||||
svgjs = stringifySvg(svgjs, config.js2svg);
|
||||
if (svgjs.data.length < prevResultSize) {
|
||||
input = svgjs.data;
|
||||
prevResultSize = svgjs.data.length;
|
||||
} else {
|
||||
if (config.datauri) {
|
||||
svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
|
||||
}
|
||||
if (config.path != null) {
|
||||
svgjs.path = config.path;
|
||||
}
|
||||
return svgjs;
|
||||
}
|
||||
}
|
||||
return svgjs;
|
||||
};
|
||||
|
||||
SVGO.prototype.optimize = function(svgstr, callback) {
|
||||
if (this.config.error) return callback(this.config);
|
||||
|
||||
var _this = this,
|
||||
config = this.config,
|
||||
maxPassCount = config.multipass ? 10 : 1,
|
||||
counter = 0,
|
||||
prevResultSize = Number.POSITIVE_INFINITY,
|
||||
optimizeOnceCallback = function(svgjs) {
|
||||
|
||||
if (svgjs.error) {
|
||||
callback(svgjs);
|
||||
return;
|
||||
}
|
||||
|
||||
if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
|
||||
prevResultSize = svgjs.data.length;
|
||||
_this._optimizeOnce(svgjs.data, optimizeOnceCallback);
|
||||
} else {
|
||||
callback(svgjs);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
_this._optimizeOnce(svgstr, optimizeOnceCallback);
|
||||
|
||||
};
|
||||
|
||||
SVGO.prototype._optimizeOnce = function(svgstr, callback) {
|
||||
var config = this.config;
|
||||
|
||||
SVG2JS(svgstr, function(svgjs) {
|
||||
|
||||
if (svgjs.error) {
|
||||
callback(svgjs);
|
||||
return;
|
||||
}
|
||||
|
||||
svgjs = PLUGINS(svgjs, config.plugins);
|
||||
|
||||
callback(JS2SVG(svgjs, config.js2svg));
|
||||
|
||||
});
|
||||
};
|
||||
exports.optimize = optimize;
|
||||
|
||||
/**
|
||||
* The factory that creates a content item with the helper methods.
|
||||
*
|
||||
* @param {Object} data which passed to jsAPI constructor
|
||||
* @param {Object} data which is passed to jsAPI constructor
|
||||
* @returns {JSAPI} content item
|
||||
*/
|
||||
SVGO.prototype.createContentItem = function(data) {
|
||||
|
||||
return new JSAPI(data);
|
||||
|
||||
const createContentItem = (data) => {
|
||||
return new JSAPI(data);
|
||||
};
|
||||
exports.createContentItem = createContentItem;
|
||||
|
||||
1042
node_modules/svgo/lib/svgo/coa.js
generated
vendored
1042
node_modules/svgo/lib/svgo/coa.js
generated
vendored
File diff suppressed because it is too large
Load Diff
328
node_modules/svgo/lib/svgo/config.js
generated
vendored
328
node_modules/svgo/lib/svgo/config.js
generated
vendored
@@ -1,212 +1,138 @@
|
||||
'use strict';
|
||||
|
||||
var FS = require('fs');
|
||||
var yaml = require('js-yaml');
|
||||
const pluginsMap = require('../../plugins/plugins.js');
|
||||
|
||||
var EXTEND = require('whet.extend');
|
||||
const pluginsOrder = [
|
||||
'removeDoctype',
|
||||
'removeXMLProcInst',
|
||||
'removeComments',
|
||||
'removeMetadata',
|
||||
'removeXMLNS',
|
||||
'removeEditorsNSData',
|
||||
'cleanupAttrs',
|
||||
'mergeStyles',
|
||||
'inlineStyles',
|
||||
'minifyStyles',
|
||||
'convertStyleToAttrs',
|
||||
'cleanupIDs',
|
||||
'prefixIds',
|
||||
'removeRasterImages',
|
||||
'removeUselessDefs',
|
||||
'cleanupNumericValues',
|
||||
'cleanupListOfValues',
|
||||
'convertColors',
|
||||
'removeUnknownsAndDefaults',
|
||||
'removeNonInheritableGroupAttrs',
|
||||
'removeUselessStrokeAndFill',
|
||||
'removeViewBox',
|
||||
'cleanupEnableBackground',
|
||||
'removeHiddenElems',
|
||||
'removeEmptyText',
|
||||
'convertShapeToPath',
|
||||
'convertEllipseToCircle',
|
||||
'moveElemsAttrsToGroup',
|
||||
'moveGroupAttrsToElems',
|
||||
'collapseGroups',
|
||||
'convertPathData',
|
||||
'convertTransform',
|
||||
'removeEmptyAttrs',
|
||||
'removeEmptyContainers',
|
||||
'mergePaths',
|
||||
'removeUnusedNS',
|
||||
'sortAttrs',
|
||||
'sortDefsChildren',
|
||||
'removeTitle',
|
||||
'removeDesc',
|
||||
'removeDimensions',
|
||||
'removeAttrs',
|
||||
'removeAttributesBySelector',
|
||||
'removeElementsByAttr',
|
||||
'addClassesToSVGElement',
|
||||
'removeStyleElement',
|
||||
'removeScriptElement',
|
||||
'addAttributesToSVGElement',
|
||||
'removeOffCanvasPaths',
|
||||
'reusePaths',
|
||||
];
|
||||
const defaultPlugins = pluginsOrder.filter((name) => pluginsMap[name].active);
|
||||
exports.defaultPlugins = defaultPlugins;
|
||||
|
||||
/**
|
||||
* Read and/or extend/replace default config file,
|
||||
* prepare and optimize plugins array.
|
||||
*
|
||||
* @param {Object} [config] input config
|
||||
* @return {Object} output config
|
||||
*/
|
||||
module.exports = function(config) {
|
||||
|
||||
var defaults;
|
||||
config = typeof config == 'object' && config || {};
|
||||
|
||||
if (config.plugins && !Array.isArray(config.plugins)) {
|
||||
return { error: 'Error: Invalid plugins list. Provided \'plugins\' in config should be an array.' };
|
||||
}
|
||||
|
||||
if (config.full) {
|
||||
defaults = config;
|
||||
|
||||
if (Array.isArray(defaults.plugins)) {
|
||||
defaults.plugins = preparePluginsArray(defaults.plugins);
|
||||
}
|
||||
const extendDefaultPlugins = (plugins) => {
|
||||
console.warn(
|
||||
'\n"extendDefaultPlugins" utility is deprecated.\n' +
|
||||
'Use "preset-default" plugin with overrides instead.\n' +
|
||||
'For example:\n' +
|
||||
`{\n` +
|
||||
` name: 'preset-default',\n` +
|
||||
` params: {\n` +
|
||||
` overrides: {\n` +
|
||||
` // customize plugin options\n` +
|
||||
` convertShapeToPath: {\n` +
|
||||
` convertArcs: true\n` +
|
||||
` },\n` +
|
||||
` // disable plugins\n` +
|
||||
` convertPathData: false\n` +
|
||||
` }\n` +
|
||||
` }\n` +
|
||||
`}\n`
|
||||
);
|
||||
const extendedPlugins = pluginsOrder.map((name) => ({
|
||||
name,
|
||||
active: pluginsMap[name].active,
|
||||
}));
|
||||
for (const plugin of plugins) {
|
||||
const resolvedPlugin = resolvePluginConfig(plugin);
|
||||
const index = pluginsOrder.indexOf(resolvedPlugin.name);
|
||||
if (index === -1) {
|
||||
extendedPlugins.push(plugin);
|
||||
} else {
|
||||
defaults = EXTEND({}, yaml.safeLoad(FS.readFileSync(__dirname + '/../../.svgo.yml', 'utf8')));
|
||||
defaults.plugins = preparePluginsArray(defaults.plugins);
|
||||
defaults = extendConfig(defaults, config);
|
||||
extendedPlugins[index] = plugin;
|
||||
}
|
||||
|
||||
if ('floatPrecision' in config && Array.isArray(defaults.plugins)) {
|
||||
defaults.plugins.forEach(function(plugin) {
|
||||
if (plugin.params && ('floatPrecision' in plugin.params)) {
|
||||
// Don't touch default plugin params
|
||||
plugin.params = EXTEND({}, plugin.params, { floatPrecision: config.floatPrecision });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(defaults.plugins)) {
|
||||
defaults.plugins = optimizePluginsArray(defaults.plugins);
|
||||
}
|
||||
|
||||
return defaults;
|
||||
|
||||
}
|
||||
return extendedPlugins;
|
||||
};
|
||||
exports.extendDefaultPlugins = extendDefaultPlugins;
|
||||
|
||||
/**
|
||||
* Require() all plugins in array.
|
||||
*
|
||||
* @param {Array} plugins input plugins array
|
||||
* @return {Array} input plugins array of arrays
|
||||
*/
|
||||
function preparePluginsArray(plugins) {
|
||||
|
||||
var plugin,
|
||||
key;
|
||||
|
||||
return plugins.map(function(item) {
|
||||
|
||||
// {}
|
||||
if (typeof item === 'object') {
|
||||
|
||||
key = Object.keys(item)[0];
|
||||
|
||||
// custom
|
||||
if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') {
|
||||
plugin = setupCustomPlugin(key, item[key]);
|
||||
|
||||
} else {
|
||||
|
||||
plugin = EXTEND({}, require('../../plugins/' + key));
|
||||
|
||||
// name: {}
|
||||
if (typeof item[key] === 'object') {
|
||||
plugin.params = EXTEND({}, plugin.params || {}, item[key]);
|
||||
plugin.active = true;
|
||||
|
||||
// name: false
|
||||
} else if (item[key] === false) {
|
||||
plugin.active = false;
|
||||
|
||||
// name: true
|
||||
} else if (item[key] === true) {
|
||||
plugin.active = true;
|
||||
}
|
||||
|
||||
plugin.name = key;
|
||||
}
|
||||
|
||||
// name
|
||||
} else {
|
||||
|
||||
plugin = EXTEND({}, require('../../plugins/' + item));
|
||||
plugin.name = item;
|
||||
|
||||
}
|
||||
|
||||
return plugin;
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Extend plugins with the custom config object.
|
||||
*
|
||||
* @param {Array} plugins input plugins
|
||||
* @param {Object} config config
|
||||
* @return {Array} output plugins
|
||||
*/
|
||||
function extendConfig(defaults, config) {
|
||||
|
||||
var key;
|
||||
|
||||
// plugins
|
||||
if (config.plugins) {
|
||||
|
||||
config.plugins.forEach(function(item) {
|
||||
|
||||
// {}
|
||||
if (typeof item === 'object') {
|
||||
|
||||
key = Object.keys(item)[0];
|
||||
|
||||
// custom
|
||||
if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') {
|
||||
defaults.plugins.push(setupCustomPlugin(key, item[key]));
|
||||
|
||||
} else {
|
||||
defaults.plugins.forEach(function(plugin) {
|
||||
|
||||
if (plugin.name === key) {
|
||||
// name: {}
|
||||
if (typeof item[key] === 'object') {
|
||||
plugin.params = EXTEND({}, plugin.params || {}, item[key]);
|
||||
plugin.active = true;
|
||||
|
||||
// name: false
|
||||
} else if (item[key] === false) {
|
||||
plugin.active = false;
|
||||
|
||||
// name: true
|
||||
} else if (item[key] === true) {
|
||||
plugin.active = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
const resolvePluginConfig = (plugin) => {
|
||||
let configParams = {};
|
||||
if (typeof plugin === 'string') {
|
||||
// resolve builtin plugin specified as string
|
||||
const pluginConfig = pluginsMap[plugin];
|
||||
if (pluginConfig == null) {
|
||||
throw Error(`Unknown builtin plugin "${plugin}" specified.`);
|
||||
}
|
||||
|
||||
defaults.multipass = config.multipass;
|
||||
|
||||
// svg2js
|
||||
if (config.svg2js) {
|
||||
defaults.svg2js = config.svg2js;
|
||||
return {
|
||||
...pluginConfig,
|
||||
name: plugin,
|
||||
active: true,
|
||||
params: { ...pluginConfig.params, ...configParams },
|
||||
};
|
||||
}
|
||||
if (typeof plugin === 'object' && plugin != null) {
|
||||
if (plugin.name == null) {
|
||||
throw Error(`Plugin name should be specified`);
|
||||
}
|
||||
|
||||
// js2svg
|
||||
if (config.js2svg) {
|
||||
defaults.js2svg = config.js2svg;
|
||||
if (plugin.fn) {
|
||||
// resolve custom plugin with implementation
|
||||
return {
|
||||
active: true,
|
||||
...plugin,
|
||||
params: { ...configParams, ...plugin.params },
|
||||
};
|
||||
} else {
|
||||
// resolve builtin plugin specified as object without implementation
|
||||
const pluginConfig = pluginsMap[plugin.name];
|
||||
if (pluginConfig == null) {
|
||||
throw Error(`Unknown builtin plugin "${plugin.name}" specified.`);
|
||||
}
|
||||
return {
|
||||
...pluginConfig,
|
||||
active: true,
|
||||
...plugin,
|
||||
params: { ...pluginConfig.params, ...configParams, ...plugin.params },
|
||||
};
|
||||
}
|
||||
|
||||
return defaults;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup and enable a custom plugin
|
||||
*
|
||||
* @param {String} plugin name
|
||||
* @param {Object} custom plugin
|
||||
* @return {Array} enabled plugin
|
||||
*/
|
||||
function setupCustomPlugin(name, plugin) {
|
||||
plugin.active = true;
|
||||
plugin.params = EXTEND({}, plugin.params || {});
|
||||
plugin.name = name;
|
||||
|
||||
return plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to group sequential elements of plugins array.
|
||||
*
|
||||
* @param {Object} plugins input plugins
|
||||
* @return {Array} output plugins
|
||||
*/
|
||||
function optimizePluginsArray(plugins) {
|
||||
|
||||
var prev;
|
||||
|
||||
return plugins.reduce(function(plugins, item) {
|
||||
if (prev && item.type == prev[0].type) {
|
||||
prev.push(item);
|
||||
} else {
|
||||
plugins.push(prev = [item]);
|
||||
}
|
||||
return plugins;
|
||||
}, []);
|
||||
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
exports.resolvePluginConfig = resolvePluginConfig;
|
||||
|
||||
72
node_modules/svgo/lib/svgo/css-class-list.js
generated
vendored
Normal file
72
node_modules/svgo/lib/svgo/css-class-list.js
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
var CSSClassList = function (node) {
|
||||
this.parentNode = node;
|
||||
this.classNames = new Set();
|
||||
const value = node.attributes.class;
|
||||
if (value != null) {
|
||||
this.addClassValueHandler();
|
||||
this.setClassValue(value);
|
||||
}
|
||||
};
|
||||
|
||||
// attr.class.value
|
||||
|
||||
CSSClassList.prototype.addClassValueHandler = function () {
|
||||
Object.defineProperty(this.parentNode.attributes, 'class', {
|
||||
get: this.getClassValue.bind(this),
|
||||
set: this.setClassValue.bind(this),
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
|
||||
CSSClassList.prototype.getClassValue = function () {
|
||||
var arrClassNames = Array.from(this.classNames);
|
||||
return arrClassNames.join(' ');
|
||||
};
|
||||
|
||||
CSSClassList.prototype.setClassValue = function (newValue) {
|
||||
if (typeof newValue === 'undefined') {
|
||||
this.classNames.clear();
|
||||
return;
|
||||
}
|
||||
var arrClassNames = newValue.split(' ');
|
||||
this.classNames = new Set(arrClassNames);
|
||||
};
|
||||
|
||||
CSSClassList.prototype.add = function (/* variadic */) {
|
||||
this.addClassValueHandler();
|
||||
Object.values(arguments).forEach(this._addSingle.bind(this));
|
||||
};
|
||||
|
||||
CSSClassList.prototype._addSingle = function (className) {
|
||||
this.classNames.add(className);
|
||||
};
|
||||
|
||||
CSSClassList.prototype.remove = function (/* variadic */) {
|
||||
this.addClassValueHandler();
|
||||
Object.values(arguments).forEach(this._removeSingle.bind(this));
|
||||
};
|
||||
|
||||
CSSClassList.prototype._removeSingle = function (className) {
|
||||
this.classNames.delete(className);
|
||||
};
|
||||
|
||||
CSSClassList.prototype.item = function (index) {
|
||||
var arrClassNames = Array.from(this.classNames);
|
||||
return arrClassNames[index];
|
||||
};
|
||||
|
||||
CSSClassList.prototype.toggle = function (className, force) {
|
||||
if (this.contains(className) || force === false) {
|
||||
this.classNames.delete(className);
|
||||
}
|
||||
this.classNames.add(className);
|
||||
};
|
||||
|
||||
CSSClassList.prototype.contains = function (className) {
|
||||
return this.classNames.has(className);
|
||||
};
|
||||
|
||||
module.exports = CSSClassList;
|
||||
2
node_modules/svgo/lib/svgo/css-select-adapter.d.ts
generated
vendored
Normal file
2
node_modules/svgo/lib/svgo/css-select-adapter.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
declare let obj: any;
|
||||
export = obj;
|
||||
120
node_modules/svgo/lib/svgo/css-select-adapter.js
generated
vendored
Normal file
120
node_modules/svgo/lib/svgo/css-select-adapter.js
generated
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
'use strict';
|
||||
|
||||
const isTag = (node) => {
|
||||
return node.type === 'element';
|
||||
};
|
||||
|
||||
const existsOne = (test, elems) => {
|
||||
return elems.some((elem) => {
|
||||
if (isTag(elem)) {
|
||||
return test(elem) || existsOne(test, getChildren(elem));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getAttributeValue = (elem, name) => {
|
||||
return elem.attributes[name];
|
||||
};
|
||||
|
||||
const getChildren = (node) => {
|
||||
return node.children || [];
|
||||
};
|
||||
|
||||
const getName = (elemAst) => {
|
||||
return elemAst.name;
|
||||
};
|
||||
|
||||
const getParent = (node) => {
|
||||
return node.parentNode || null;
|
||||
};
|
||||
|
||||
const getSiblings = (elem) => {
|
||||
var parent = getParent(elem);
|
||||
return parent ? getChildren(parent) : [];
|
||||
};
|
||||
|
||||
const getText = (node) => {
|
||||
if (node.children[0].type === 'text' && node.children[0].type === 'cdata') {
|
||||
return node.children[0].value;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const hasAttrib = (elem, name) => {
|
||||
return elem.attributes[name] !== undefined;
|
||||
};
|
||||
|
||||
const removeSubsets = (nodes) => {
|
||||
let idx = nodes.length;
|
||||
let node;
|
||||
let ancestor;
|
||||
let replace;
|
||||
// Check if each node (or one of its ancestors) is already contained in the
|
||||
// array.
|
||||
while (--idx > -1) {
|
||||
node = ancestor = nodes[idx];
|
||||
// Temporarily remove the node under consideration
|
||||
nodes[idx] = null;
|
||||
replace = true;
|
||||
while (ancestor) {
|
||||
if (nodes.includes(ancestor)) {
|
||||
replace = false;
|
||||
nodes.splice(idx, 1);
|
||||
break;
|
||||
}
|
||||
ancestor = getParent(ancestor);
|
||||
}
|
||||
// If the node has been found to be unique, re-insert it.
|
||||
if (replace) {
|
||||
nodes[idx] = node;
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
};
|
||||
|
||||
const findAll = (test, elems) => {
|
||||
const result = [];
|
||||
for (const elem of elems) {
|
||||
if (isTag(elem)) {
|
||||
if (test(elem)) {
|
||||
result.push(elem);
|
||||
}
|
||||
result.push(...findAll(test, getChildren(elem)));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const findOne = (test, elems) => {
|
||||
for (const elem of elems) {
|
||||
if (isTag(elem)) {
|
||||
if (test(elem)) {
|
||||
return elem;
|
||||
}
|
||||
const result = findOne(test, getChildren(elem));
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const svgoCssSelectAdapter = {
|
||||
isTag,
|
||||
existsOne,
|
||||
getAttributeValue,
|
||||
getChildren,
|
||||
getName,
|
||||
getParent,
|
||||
getSiblings,
|
||||
getText,
|
||||
hasAttrib,
|
||||
removeSubsets,
|
||||
findAll,
|
||||
findOne,
|
||||
};
|
||||
|
||||
module.exports = svgoCssSelectAdapter;
|
||||
232
node_modules/svgo/lib/svgo/css-style-declaration.js
generated
vendored
Normal file
232
node_modules/svgo/lib/svgo/css-style-declaration.js
generated
vendored
Normal file
@@ -0,0 +1,232 @@
|
||||
'use strict';
|
||||
|
||||
var csstree = require('css-tree'),
|
||||
csstools = require('../css-tools');
|
||||
|
||||
var CSSStyleDeclaration = function (node) {
|
||||
this.parentNode = node;
|
||||
|
||||
this.properties = new Map();
|
||||
this.hasSynced = false;
|
||||
|
||||
this.styleValue = null;
|
||||
|
||||
this.parseError = false;
|
||||
const value = node.attributes.style;
|
||||
if (value != null) {
|
||||
this.addStyleValueHandler();
|
||||
this.setStyleValue(value);
|
||||
}
|
||||
};
|
||||
|
||||
// attr.style.value
|
||||
|
||||
CSSStyleDeclaration.prototype.addStyleValueHandler = function () {
|
||||
Object.defineProperty(this.parentNode.attributes, 'style', {
|
||||
get: this.getStyleValue.bind(this),
|
||||
set: this.setStyleValue.bind(this),
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
|
||||
CSSStyleDeclaration.prototype.getStyleValue = function () {
|
||||
return this.getCssText();
|
||||
};
|
||||
|
||||
CSSStyleDeclaration.prototype.setStyleValue = function (newValue) {
|
||||
this.properties.clear(); // reset all existing properties
|
||||
this.styleValue = newValue;
|
||||
this.hasSynced = false; // raw css changed
|
||||
};
|
||||
|
||||
CSSStyleDeclaration.prototype._loadCssText = function () {
|
||||
if (this.hasSynced) {
|
||||
return;
|
||||
}
|
||||
this.hasSynced = true; // must be set here to prevent loop in setProperty(...)
|
||||
|
||||
if (!this.styleValue || this.styleValue.length === 0) {
|
||||
return;
|
||||
}
|
||||
var inlineCssStr = this.styleValue;
|
||||
|
||||
var declarations = {};
|
||||
try {
|
||||
declarations = csstree.parse(inlineCssStr, {
|
||||
context: 'declarationList',
|
||||
parseValue: false,
|
||||
});
|
||||
} catch (parseError) {
|
||||
this.parseError = parseError;
|
||||
return;
|
||||
}
|
||||
this.parseError = false;
|
||||
|
||||
var self = this;
|
||||
declarations.children.each(function (declaration) {
|
||||
try {
|
||||
var styleDeclaration = csstools.csstreeToStyleDeclaration(declaration);
|
||||
self.setProperty(
|
||||
styleDeclaration.name,
|
||||
styleDeclaration.value,
|
||||
styleDeclaration.priority
|
||||
);
|
||||
} catch (styleError) {
|
||||
if (styleError.message !== 'Unknown node type: undefined') {
|
||||
self.parseError = styleError;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// only reads from properties
|
||||
|
||||
/**
|
||||
* Get the textual representation of the declaration block (equivalent to .cssText attribute).
|
||||
*
|
||||
* @return {string} Textual representation of the declaration block (empty string for no properties)
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.getCssText = function () {
|
||||
var properties = this.getProperties();
|
||||
|
||||
if (this.parseError) {
|
||||
// in case of a parse error, pass through original styles
|
||||
return this.styleValue;
|
||||
}
|
||||
|
||||
var cssText = [];
|
||||
properties.forEach(function (property, propertyName) {
|
||||
var strImportant = property.priority === 'important' ? '!important' : '';
|
||||
cssText.push(
|
||||
propertyName.trim() + ':' + property.value.trim() + strImportant
|
||||
);
|
||||
});
|
||||
return cssText.join(';');
|
||||
};
|
||||
|
||||
CSSStyleDeclaration.prototype._handleParseError = function () {
|
||||
if (this.parseError) {
|
||||
console.warn(
|
||||
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
|
||||
this.parseError
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
CSSStyleDeclaration.prototype._getProperty = function (propertyName) {
|
||||
if (typeof propertyName === 'undefined') {
|
||||
throw Error('1 argument required, but only 0 present.');
|
||||
}
|
||||
|
||||
var properties = this.getProperties();
|
||||
this._handleParseError();
|
||||
|
||||
var property = properties.get(propertyName.trim());
|
||||
return property;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the optional priority, "important".
|
||||
*
|
||||
* @param {string} propertyName representing the property name to be checked.
|
||||
* @return {string} priority that represents the priority (e.g. "important") if one exists. If none exists, returns the empty string.
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.getPropertyPriority = function (propertyName) {
|
||||
var property = this._getProperty(propertyName);
|
||||
return property ? property.priority : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the property value given a property name.
|
||||
*
|
||||
* @param {string} propertyName representing the property name to be checked.
|
||||
* @return {string} value containing the value of the property. If not set, returns the empty string.
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.getPropertyValue = function (propertyName) {
|
||||
var property = this._getProperty(propertyName);
|
||||
return property ? property.value : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a property name.
|
||||
*
|
||||
* @param {number} index of the node to be fetched. The index is zero-based.
|
||||
* @return {string} propertyName that is the name of the CSS property at the specified index.
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.item = function (index) {
|
||||
if (typeof index === 'undefined') {
|
||||
throw Error('1 argument required, but only 0 present.');
|
||||
}
|
||||
|
||||
var properties = this.getProperties();
|
||||
this._handleParseError();
|
||||
|
||||
return Array.from(properties.keys())[index];
|
||||
};
|
||||
|
||||
/**
|
||||
* Return all properties of the node.
|
||||
*
|
||||
* @return {Map} properties that is a Map with propertyName as key and property (propertyValue + propertyPriority) as value.
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.getProperties = function () {
|
||||
this._loadCssText();
|
||||
return this.properties;
|
||||
};
|
||||
|
||||
// writes to properties
|
||||
|
||||
/**
|
||||
* Remove a property from the CSS declaration block.
|
||||
*
|
||||
* @param {string} propertyName representing the property name to be removed.
|
||||
* @return {string} oldValue equal to the value of the CSS property before it was removed.
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.removeProperty = function (propertyName) {
|
||||
if (typeof propertyName === 'undefined') {
|
||||
throw Error('1 argument required, but only 0 present.');
|
||||
}
|
||||
|
||||
this.addStyleValueHandler();
|
||||
|
||||
var properties = this.getProperties();
|
||||
this._handleParseError();
|
||||
|
||||
var oldValue = this.getPropertyValue(propertyName);
|
||||
properties.delete(propertyName.trim());
|
||||
return oldValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Modify an existing CSS property or creates a new CSS property in the declaration block.
|
||||
*
|
||||
* @param {string} propertyName representing the CSS property name to be modified.
|
||||
* @param {string} value containing the new property value. If not specified, treated as the empty string. value must not contain "!important" -- that should be set using the priority parameter.
|
||||
* @param {string} priority allowing the "important" CSS priority to be set. If not specified, treated as the empty string.
|
||||
* @return {{value: string, priority: string}}
|
||||
*/
|
||||
CSSStyleDeclaration.prototype.setProperty = function (
|
||||
propertyName,
|
||||
value,
|
||||
priority
|
||||
) {
|
||||
if (typeof propertyName === 'undefined') {
|
||||
throw Error('propertyName argument required, but only not present.');
|
||||
}
|
||||
|
||||
this.addStyleValueHandler();
|
||||
|
||||
var properties = this.getProperties();
|
||||
this._handleParseError();
|
||||
|
||||
var property = {
|
||||
value: value.trim(),
|
||||
priority: priority.trim(),
|
||||
};
|
||||
properties.set(propertyName.trim(), property);
|
||||
|
||||
return property;
|
||||
};
|
||||
|
||||
module.exports = CSSStyleDeclaration;
|
||||
344
node_modules/svgo/lib/svgo/js2svg.js
generated
vendored
344
node_modules/svgo/lib/svgo/js2svg.js
generated
vendored
@@ -1,344 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var EXTEND = require('whet.extend'),
|
||||
textElem = require('../../plugins/_collections.js').elemsGroups.textContent.concat('title');
|
||||
|
||||
var defaults = {
|
||||
doctypeStart: '<!DOCTYPE',
|
||||
doctypeEnd: '>',
|
||||
procInstStart: '<?',
|
||||
procInstEnd: '?>',
|
||||
tagOpenStart: '<',
|
||||
tagOpenEnd: '>',
|
||||
tagCloseStart: '</',
|
||||
tagCloseEnd: '>',
|
||||
tagShortStart: '<',
|
||||
tagShortEnd: '/>',
|
||||
attrStart: '="',
|
||||
attrEnd: '"',
|
||||
commentStart: '<!--',
|
||||
commentEnd: '-->',
|
||||
cdataStart: '<![CDATA[',
|
||||
cdataEnd: ']]>',
|
||||
textStart: '',
|
||||
textEnd: '',
|
||||
indent: 4,
|
||||
regEntities: /[&'"<>]/g,
|
||||
regValEntities: /[&"<>]/g,
|
||||
encodeEntity: encodeEntity,
|
||||
pretty: false,
|
||||
useShortTags: true
|
||||
};
|
||||
|
||||
var entities = {
|
||||
'&': '&',
|
||||
'\'': ''',
|
||||
'"': '"',
|
||||
'>': '>',
|
||||
'<': '<',
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert SVG-as-JS object to SVG (XML) string.
|
||||
*
|
||||
* @param {Object} data input data
|
||||
* @param {Object} config config
|
||||
*
|
||||
* @return {Object} output data
|
||||
*/
|
||||
module.exports = function(data, config) {
|
||||
|
||||
return new JS2SVG(config).convert(data);
|
||||
|
||||
};
|
||||
|
||||
function JS2SVG(config) {
|
||||
|
||||
if (config) {
|
||||
this.config = EXTEND(true, {}, defaults, config);
|
||||
} else {
|
||||
this.config = defaults;
|
||||
}
|
||||
|
||||
var indent = this.config.indent;
|
||||
if (typeof indent == 'number' && !isNaN(indent)) {
|
||||
this.config.indent = '';
|
||||
for (var i = indent; i-- > 0;) this.config.indent += ' ';
|
||||
} else if (typeof indent != 'string') {
|
||||
this.config.indent = ' ';
|
||||
}
|
||||
|
||||
if (this.config.pretty) {
|
||||
this.config.doctypeEnd += '\n';
|
||||
this.config.procInstEnd += '\n';
|
||||
this.config.commentEnd += '\n';
|
||||
this.config.cdataEnd += '\n';
|
||||
this.config.tagShortEnd += '\n';
|
||||
this.config.tagOpenEnd += '\n';
|
||||
this.config.tagCloseEnd += '\n';
|
||||
this.config.textEnd += '\n';
|
||||
}
|
||||
|
||||
this.indentLevel = 0;
|
||||
this.textContext = null;
|
||||
|
||||
}
|
||||
|
||||
function encodeEntity(char) {
|
||||
return entities[char];
|
||||
}
|
||||
|
||||
/**
|
||||
* Start conversion.
|
||||
*
|
||||
* @param {Object} data input data
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.convert = function(data) {
|
||||
|
||||
var svg = '';
|
||||
|
||||
if (data.content) {
|
||||
|
||||
this.indentLevel++;
|
||||
|
||||
data.content.forEach(function(item) {
|
||||
|
||||
if (item.elem) {
|
||||
svg += this.createElem(item);
|
||||
} else if (item.text) {
|
||||
svg += this.createText(item.text);
|
||||
} else if (item.doctype) {
|
||||
svg += this.createDoctype(item.doctype);
|
||||
} else if (item.processinginstruction) {
|
||||
svg += this.createProcInst(item.processinginstruction);
|
||||
} else if (item.comment) {
|
||||
svg += this.createComment(item.comment);
|
||||
} else if (item.cdata) {
|
||||
svg += this.createCDATA(item.cdata);
|
||||
}
|
||||
|
||||
}, this);
|
||||
|
||||
}
|
||||
|
||||
this.indentLevel--;
|
||||
|
||||
return {
|
||||
data: svg,
|
||||
info: {
|
||||
width: this.width,
|
||||
height: this.height
|
||||
}
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create indent string in accordance with the current node level.
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createIndent = function() {
|
||||
|
||||
var indent = '';
|
||||
|
||||
if (this.config.pretty && !this.textContext) {
|
||||
for (var i = 1; i < this.indentLevel; i++) {
|
||||
indent += this.config.indent;
|
||||
}
|
||||
}
|
||||
|
||||
return indent;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create doctype tag.
|
||||
*
|
||||
* @param {String} doctype doctype body string
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createDoctype = function(doctype) {
|
||||
|
||||
return this.config.doctypeStart +
|
||||
doctype +
|
||||
this.config.doctypeEnd;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create XML Processing Instruction tag.
|
||||
*
|
||||
* @param {Object} instruction instruction object
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createProcInst = function(instruction) {
|
||||
|
||||
return this.config.procInstStart +
|
||||
instruction.name +
|
||||
' ' +
|
||||
instruction.body +
|
||||
this.config.procInstEnd;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create comment tag.
|
||||
*
|
||||
* @param {String} comment comment body
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createComment = function(comment) {
|
||||
|
||||
return this.config.commentStart +
|
||||
comment +
|
||||
this.config.commentEnd;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create CDATA section.
|
||||
*
|
||||
* @param {String} cdata CDATA body
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createCDATA = function(cdata) {
|
||||
|
||||
return this.createIndent() +
|
||||
this.config.cdataStart +
|
||||
cdata +
|
||||
this.config.cdataEnd;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create element tag.
|
||||
*
|
||||
* @param {Object} data element object
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createElem = function(data) {
|
||||
|
||||
// beautiful injection for obtaining SVG information :)
|
||||
if (
|
||||
data.isElem('svg') &&
|
||||
data.hasAttr('width') &&
|
||||
data.hasAttr('height')
|
||||
) {
|
||||
this.width = data.attr('width').value;
|
||||
this.height = data.attr('height').value;
|
||||
}
|
||||
|
||||
// empty element and short tag
|
||||
if (data.isEmpty()) {
|
||||
if (this.config.useShortTags) {
|
||||
return this.createIndent() +
|
||||
this.config.tagShortStart +
|
||||
data.elem +
|
||||
this.createAttrs(data) +
|
||||
this.config.tagShortEnd;
|
||||
} else {
|
||||
return this.createIndent() +
|
||||
this.config.tagShortStart +
|
||||
data.elem +
|
||||
this.createAttrs(data) +
|
||||
this.config.tagOpenEnd +
|
||||
this.config.tagCloseStart +
|
||||
data.elem +
|
||||
this.config.tagCloseEnd;
|
||||
}
|
||||
// non-empty element
|
||||
} else {
|
||||
var tagOpenStart = this.config.tagOpenStart,
|
||||
tagOpenEnd = this.config.tagOpenEnd,
|
||||
tagCloseStart = this.config.tagCloseStart,
|
||||
tagCloseEnd = this.config.tagCloseEnd,
|
||||
openIndent = this.createIndent(),
|
||||
textIndent = '',
|
||||
processedData = '',
|
||||
dataEnd = '';
|
||||
|
||||
if (this.textContext) {
|
||||
tagOpenStart = defaults.tagOpenStart;
|
||||
tagOpenEnd = defaults.tagOpenEnd;
|
||||
tagCloseStart = defaults.tagCloseStart;
|
||||
tagCloseEnd = defaults.tagCloseEnd;
|
||||
openIndent = '';
|
||||
} else if (data.isElem(textElem)) {
|
||||
if (this.config.pretty) {
|
||||
textIndent += openIndent + this.config.indent;
|
||||
}
|
||||
this.textContext = data;
|
||||
}
|
||||
|
||||
processedData += this.convert(data).data;
|
||||
|
||||
if (this.textContext == data) {
|
||||
this.textContext = null;
|
||||
if (this.config.pretty) dataEnd = '\n';
|
||||
}
|
||||
|
||||
return openIndent +
|
||||
tagOpenStart +
|
||||
data.elem +
|
||||
this.createAttrs(data) +
|
||||
tagOpenEnd +
|
||||
textIndent +
|
||||
processedData +
|
||||
dataEnd +
|
||||
this.createIndent() +
|
||||
tagCloseStart +
|
||||
data.elem +
|
||||
tagCloseEnd;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create element attributes.
|
||||
*
|
||||
* @param {Object} elem attributes object
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createAttrs = function(elem) {
|
||||
|
||||
var attrs = '';
|
||||
|
||||
elem.eachAttr(function(attr) {
|
||||
|
||||
attrs += ' ' +
|
||||
attr.name +
|
||||
this.config.attrStart +
|
||||
String(attr.value).replace(this.config.regValEntities, this.config.encodeEntity) +
|
||||
this.config.attrEnd;
|
||||
|
||||
}, this);
|
||||
|
||||
return attrs;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Create text node.
|
||||
*
|
||||
* @param {String} text text
|
||||
*
|
||||
* @return {String}
|
||||
*/
|
||||
JS2SVG.prototype.createText = function(text) {
|
||||
|
||||
return this.createIndent() +
|
||||
this.config.textStart +
|
||||
text.replace(this.config.regEntities, this.config.encodeEntity) +
|
||||
(this.textContext ? '' : this.config.textEnd);
|
||||
|
||||
};
|
||||
2
node_modules/svgo/lib/svgo/jsAPI.d.ts
generated
vendored
Normal file
2
node_modules/svgo/lib/svgo/jsAPI.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
declare let obj: any;
|
||||
export = obj;
|
||||
470
node_modules/svgo/lib/svgo/jsAPI.js
generated
vendored
470
node_modules/svgo/lib/svgo/jsAPI.js
generated
vendored
@@ -1,50 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
var EXTEND = require('whet.extend');
|
||||
const { selectAll, selectOne, is } = require('css-select');
|
||||
const svgoCssSelectAdapter = require('./css-select-adapter');
|
||||
const CSSClassList = require('./css-class-list');
|
||||
const CSSStyleDeclaration = require('./css-style-declaration');
|
||||
|
||||
var JSAPI = module.exports = function(data, parentNode) {
|
||||
EXTEND(this, data);
|
||||
if (parentNode) {
|
||||
Object.defineProperty(this, 'parentNode', {
|
||||
writable: true,
|
||||
value: parentNode
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @type {(name: string) => { prefix: string, local: string }}
|
||||
*/
|
||||
const parseName = (name) => {
|
||||
if (name == null) {
|
||||
return {
|
||||
prefix: '',
|
||||
local: '',
|
||||
};
|
||||
}
|
||||
if (name === 'xmlns') {
|
||||
return {
|
||||
prefix: 'xmlns',
|
||||
local: '',
|
||||
};
|
||||
}
|
||||
const chunks = name.split(':');
|
||||
if (chunks.length === 1) {
|
||||
return {
|
||||
prefix: '',
|
||||
local: chunks[0],
|
||||
};
|
||||
}
|
||||
return {
|
||||
prefix: chunks[0],
|
||||
local: chunks[1],
|
||||
};
|
||||
};
|
||||
|
||||
var cssSelectOpts = {
|
||||
xmlMode: true,
|
||||
adapter: svgoCssSelectAdapter,
|
||||
};
|
||||
|
||||
const attrsHandler = {
|
||||
get: (attributes, name) => {
|
||||
// eslint-disable-next-line no-prototype-builtins
|
||||
if (attributes.hasOwnProperty(name)) {
|
||||
return {
|
||||
name,
|
||||
get value() {
|
||||
return attributes[name];
|
||||
},
|
||||
set value(value) {
|
||||
attributes[name] = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
set: (attributes, name, attr) => {
|
||||
attributes[name] = attr.value;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
var JSAPI = function (data, parentNode) {
|
||||
Object.assign(this, data);
|
||||
if (this.type === 'element') {
|
||||
if (this.attributes == null) {
|
||||
this.attributes = {};
|
||||
}
|
||||
if (this.children == null) {
|
||||
this.children = [];
|
||||
}
|
||||
Object.defineProperty(this, 'class', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: new CSSClassList(this),
|
||||
});
|
||||
Object.defineProperty(this, 'style', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: new CSSStyleDeclaration(this),
|
||||
});
|
||||
Object.defineProperty(this, 'parentNode', {
|
||||
writable: true,
|
||||
value: parentNode,
|
||||
});
|
||||
|
||||
// temporary attrs polyfill
|
||||
// TODO remove after migration
|
||||
const element = this;
|
||||
Object.defineProperty(this, 'attrs', {
|
||||
configurable: true,
|
||||
get() {
|
||||
return new Proxy(element.attributes, attrsHandler);
|
||||
},
|
||||
set(value) {
|
||||
const newAttributes = {};
|
||||
for (const attr of Object.values(value)) {
|
||||
newAttributes[attr.name] = attr.value;
|
||||
}
|
||||
element.attributes = newAttributes;
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
module.exports = JSAPI;
|
||||
|
||||
/**
|
||||
* Perform a deep clone of this node.
|
||||
*
|
||||
* @return {Object} element
|
||||
*/
|
||||
JSAPI.prototype.clone = function() {
|
||||
var node = this;
|
||||
var nodeData = {};
|
||||
|
||||
Object.keys(node).forEach(function(key) {
|
||||
if (key !== 'content') {
|
||||
nodeData[key] = node[key];
|
||||
}
|
||||
JSAPI.prototype.clone = function () {
|
||||
const { children, ...nodeData } = this;
|
||||
// Deep-clone node data.
|
||||
const clonedNode = new JSAPI(JSON.parse(JSON.stringify(nodeData)), null);
|
||||
if (children) {
|
||||
clonedNode.children = children.map((child) => {
|
||||
const clonedChild = child.clone();
|
||||
clonedChild.parentNode = clonedNode;
|
||||
return clonedChild;
|
||||
});
|
||||
|
||||
// Deep-clone node data
|
||||
// This is still faster than using EXTEND(true…)
|
||||
nodeData = JSON.parse(JSON.stringify(nodeData));
|
||||
|
||||
// parentNode gets set to a proper object by the parent clone,
|
||||
// but it needs to be true/false now to do the right thing
|
||||
// in the constructor.
|
||||
var clonedNode = new JSAPI(nodeData, !!node.parentNode);
|
||||
|
||||
if (node.content) {
|
||||
clonedNode.content = node.content.map(function(childNode) {
|
||||
var clonedChild = childNode.clone();
|
||||
clonedChild.parentNode = clonedNode;
|
||||
return clonedChild;
|
||||
});
|
||||
}
|
||||
|
||||
return clonedNode;
|
||||
}
|
||||
return clonedNode;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -54,14 +130,17 @@ JSAPI.prototype.clone = function() {
|
||||
* @param {String|Array} [param] element name or names arrays
|
||||
* @return {Boolean}
|
||||
*/
|
||||
JSAPI.prototype.isElem = function(param) {
|
||||
|
||||
if (!param) return !!this.elem;
|
||||
|
||||
if (Array.isArray(param)) return !!this.elem && (param.indexOf(this.elem) > -1);
|
||||
|
||||
return !!this.elem && this.elem === param;
|
||||
|
||||
JSAPI.prototype.isElem = function (param) {
|
||||
if (this.type !== 'element') {
|
||||
return false;
|
||||
}
|
||||
if (param == null) {
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(param)) {
|
||||
return param.includes(this.name);
|
||||
}
|
||||
return this.name === param;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -70,13 +149,10 @@ JSAPI.prototype.isElem = function(param) {
|
||||
* @param {String} name new element name
|
||||
* @return {Object} element
|
||||
*/
|
||||
JSAPI.prototype.renameElem = function(name) {
|
||||
|
||||
if (name && typeof name === 'string')
|
||||
this.elem = this.local = name;
|
||||
|
||||
return this;
|
||||
JSAPI.prototype.renameElem = function (name) {
|
||||
if (name && typeof name === 'string') this.name = name;
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -84,32 +160,46 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
*
|
||||
* @return {Boolean}
|
||||
*/
|
||||
JSAPI.prototype.isEmpty = function() {
|
||||
|
||||
return !this.content || !this.content.length;
|
||||
|
||||
JSAPI.prototype.isEmpty = function () {
|
||||
return !this.children || !this.children.length;
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes content by removing elements and/or adding new elements.
|
||||
* Find the closest ancestor of the current element.
|
||||
* @param elemName
|
||||
*
|
||||
* @param {Number} start Index at which to start changing the content.
|
||||
* @return {?Object}
|
||||
*/
|
||||
JSAPI.prototype.closestElem = function (elemName) {
|
||||
var elem = this;
|
||||
|
||||
while ((elem = elem.parentNode) && !elem.isElem(elemName));
|
||||
|
||||
return elem;
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes children by removing elements and/or adding new elements.
|
||||
*
|
||||
* @param {Number} start Index at which to start changing the children.
|
||||
* @param {Number} n Number of elements to remove.
|
||||
* @param {Array|Object} [insertion] Elements to add to the content.
|
||||
* @param {Array|Object} [insertion] Elements to add to the children.
|
||||
* @return {Array} Removed elements.
|
||||
*/
|
||||
JSAPI.prototype.spliceContent = function(start, n, insertion) {
|
||||
JSAPI.prototype.spliceContent = function (start, n, insertion) {
|
||||
if (arguments.length < 2) return [];
|
||||
|
||||
if (arguments.length < 2) return [];
|
||||
|
||||
if (!Array.isArray(insertion))
|
||||
insertion = Array.apply(null, arguments).slice(2);
|
||||
|
||||
insertion.forEach(function(inner) { inner.parentNode = this }, this);
|
||||
|
||||
return this.content.splice.apply(this.content, [start, n].concat(insertion));
|
||||
if (!Array.isArray(insertion))
|
||||
insertion = Array.apply(null, arguments).slice(2);
|
||||
|
||||
insertion.forEach(function (inner) {
|
||||
inner.parentNode = this;
|
||||
}, this);
|
||||
|
||||
return this.children.splice.apply(
|
||||
this.children,
|
||||
[start, n].concat(insertion)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -120,16 +210,24 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {String} [val] attribute value (will be toString()'ed)
|
||||
* @return {Boolean}
|
||||
*/
|
||||
JSAPI.prototype.hasAttr = function(name, val) {
|
||||
|
||||
if (!this.attrs || !Object.keys(this.attrs).length) return false;
|
||||
|
||||
if (!arguments.length) return !!this.attrs;
|
||||
|
||||
if (val !== undefined) return !!this.attrs[name] && this.attrs[name].value === val.toString();
|
||||
|
||||
return !!this.attrs[name];
|
||||
|
||||
JSAPI.prototype.hasAttr = function (name, val) {
|
||||
if (this.type !== 'element') {
|
||||
return false;
|
||||
}
|
||||
if (Object.keys(this.attributes).length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (name == null) {
|
||||
return true;
|
||||
}
|
||||
// eslint-disable-next-line no-prototype-builtins
|
||||
if (this.attributes.hasOwnProperty(name) === false) {
|
||||
return false;
|
||||
}
|
||||
if (val !== undefined) {
|
||||
return this.attributes[name] === val.toString();
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -140,39 +238,48 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {Number|String|RegExp|Function} [val] attribute value (will be toString()'ed or executed, otherwise ignored)
|
||||
* @return {Boolean}
|
||||
*/
|
||||
JSAPI.prototype.hasAttrLocal = function(localName, val) {
|
||||
JSAPI.prototype.hasAttrLocal = function (localName, val) {
|
||||
if (!this.attrs || !Object.keys(this.attrs).length) return false;
|
||||
|
||||
if (!this.attrs || !Object.keys(this.attrs).length) return false;
|
||||
if (!arguments.length) return !!this.attrs;
|
||||
|
||||
if (!arguments.length) return !!this.attrs;
|
||||
var callback;
|
||||
|
||||
var callback;
|
||||
switch (val != null && val.constructor && val.constructor.name) {
|
||||
case 'Number': // same as String
|
||||
case 'String':
|
||||
callback = stringValueTest;
|
||||
break;
|
||||
case 'RegExp':
|
||||
callback = regexpValueTest;
|
||||
break;
|
||||
case 'Function':
|
||||
callback = funcValueTest;
|
||||
break;
|
||||
default:
|
||||
callback = nameTest;
|
||||
}
|
||||
return this.someAttr(callback);
|
||||
|
||||
switch (val != null && val.constructor && val.constructor.name) {
|
||||
case 'Number': // same as String
|
||||
case 'String': callback = stringValueTest; break;
|
||||
case 'RegExp': callback = regexpValueTest; break;
|
||||
case 'Function': callback = funcValueTest; break;
|
||||
default: callback = nameTest;
|
||||
}
|
||||
return this.someAttr(callback);
|
||||
function nameTest(attr) {
|
||||
const { local } = parseName(attr.name);
|
||||
return local === localName;
|
||||
}
|
||||
|
||||
function nameTest(attr) {
|
||||
return attr.local === localName;
|
||||
}
|
||||
function stringValueTest(attr) {
|
||||
const { local } = parseName(attr.name);
|
||||
return local === localName && val == attr.value;
|
||||
}
|
||||
|
||||
function stringValueTest(attr) {
|
||||
return attr.local === localName && val == attr.value;
|
||||
}
|
||||
|
||||
function regexpValueTest(attr) {
|
||||
return attr.local === localName && val.test(attr.value);
|
||||
}
|
||||
|
||||
function funcValueTest(attr) {
|
||||
return attr.local === localName && val(attr.value);
|
||||
}
|
||||
function regexpValueTest(attr) {
|
||||
const { local } = parseName(attr.name);
|
||||
return local === localName && val.test(attr.value);
|
||||
}
|
||||
|
||||
function funcValueTest(attr) {
|
||||
const { local } = parseName(attr.name);
|
||||
return local === localName && val(attr.value);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -183,14 +290,10 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {String} [val] attribute value (will be toString()'ed)
|
||||
* @return {Object|Undefined}
|
||||
*/
|
||||
JSAPI.prototype.attr = function(name, val) {
|
||||
|
||||
if (!this.hasAttr() || !arguments.length) return undefined;
|
||||
|
||||
if (val !== undefined) return this.hasAttr(name, val) ? this.attrs[name] : undefined;
|
||||
|
||||
JSAPI.prototype.attr = function (name, val) {
|
||||
if (this.hasAttr(name, val)) {
|
||||
return this.attrs[name];
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -199,18 +302,20 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {String} name attribute name
|
||||
* @return {Object|Undefined}
|
||||
*/
|
||||
JSAPI.prototype.computedAttr = function(name, val) {
|
||||
/* jshint eqnull: true */
|
||||
if (!arguments.length) return;
|
||||
JSAPI.prototype.computedAttr = function (name, val) {
|
||||
if (!arguments.length) return;
|
||||
|
||||
for (var elem = this; elem && (!elem.hasAttr(name) || !elem.attr(name).value); elem = elem.parentNode);
|
||||
|
||||
if (val != null) {
|
||||
return elem ? elem.hasAttr(name, val) : false;
|
||||
} else if (elem && elem.hasAttr(name)) {
|
||||
return elem.attrs[name].value;
|
||||
}
|
||||
for (
|
||||
var elem = this;
|
||||
elem && (!elem.hasAttr(name) || !elem.attributes[name]);
|
||||
elem = elem.parentNode
|
||||
);
|
||||
|
||||
if (val != null) {
|
||||
return elem ? elem.hasAttr(name, val) : false;
|
||||
} else if (elem && elem.hasAttr(name)) {
|
||||
return elem.attributes[name];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -220,22 +325,24 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {String} [val] attribute value
|
||||
* @return {Boolean}
|
||||
*/
|
||||
JSAPI.prototype.removeAttr = function(name, val, recursive) {
|
||||
|
||||
if (!arguments.length) return false;
|
||||
|
||||
if (Array.isArray(name)) name.forEach(this.removeAttr, this);
|
||||
|
||||
if (!this.hasAttr(name)) return false;
|
||||
|
||||
if (!recursive && val && this.attrs[name].value !== val) return false;
|
||||
|
||||
delete this.attrs[name];
|
||||
|
||||
if (!Object.keys(this.attrs).length) delete this.attrs;
|
||||
|
||||
return true;
|
||||
|
||||
JSAPI.prototype.removeAttr = function (name, val) {
|
||||
if (this.type !== 'element') {
|
||||
return false;
|
||||
}
|
||||
if (arguments.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(name)) {
|
||||
for (const nameItem of name) {
|
||||
this.removeAttr(nameItem, val);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (this.hasAttr(name, val) === false) {
|
||||
return false;
|
||||
}
|
||||
delete this.attributes[name];
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -244,20 +351,24 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {Object} [attr={}] attribute object
|
||||
* @return {Object|Boolean} created attribute or false if no attr was passed in
|
||||
*/
|
||||
JSAPI.prototype.addAttr = function(attr) {
|
||||
attr = attr || {};
|
||||
JSAPI.prototype.addAttr = function (attr) {
|
||||
attr = attr || {};
|
||||
|
||||
if (attr.name === undefined ||
|
||||
attr.value === undefined ||
|
||||
attr.prefix === undefined ||
|
||||
attr.local === undefined
|
||||
) return false;
|
||||
if (attr.name === undefined) return false;
|
||||
|
||||
this.attrs = this.attrs || {};
|
||||
this.attrs[attr.name] = attr;
|
||||
this.attributes[attr.name] = attr.value;
|
||||
|
||||
return this.attrs[attr.name];
|
||||
if (attr.name === 'class') {
|
||||
// newly added class attribute
|
||||
this.class.addClassValueHandler();
|
||||
}
|
||||
|
||||
if (attr.name === 'style') {
|
||||
// newly added style attribute
|
||||
this.style.addStyleValueHandler();
|
||||
}
|
||||
|
||||
return this.attrs[attr.name];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -267,16 +378,17 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {Object} [context] callback context
|
||||
* @return {Boolean} false if there are no any attributes
|
||||
*/
|
||||
JSAPI.prototype.eachAttr = function(callback, context) {
|
||||
|
||||
if (!this.hasAttr()) return false;
|
||||
|
||||
for (var name in this.attrs) {
|
||||
callback.call(context, this.attrs[name]);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
JSAPI.prototype.eachAttr = function (callback, context) {
|
||||
if (this.type !== 'element') {
|
||||
return false;
|
||||
}
|
||||
if (callback == null) {
|
||||
return false;
|
||||
}
|
||||
for (const attr of Object.values(this.attrs)) {
|
||||
callback.call(context, attr);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -286,14 +398,46 @@ JSAPI.prototype.renameElem = function(name) {
|
||||
* @param {Object} [context] callback context
|
||||
* @return {Boolean} false if there are no any attributes
|
||||
*/
|
||||
JSAPI.prototype.someAttr = function(callback, context) {
|
||||
|
||||
if (!this.hasAttr()) return false;
|
||||
|
||||
for (var name in this.attrs) {
|
||||
if (callback.call(context, this.attrs[name])) return true;
|
||||
}
|
||||
|
||||
JSAPI.prototype.someAttr = function (callback, context) {
|
||||
if (this.type !== 'element') {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const attr of Object.values(this.attrs)) {
|
||||
if (callback.call(context, attr)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Evaluate a string of CSS selectors against the element and returns matched elements.
|
||||
*
|
||||
* @param {String} selectors CSS selector(s) string
|
||||
* @return {Array} null if no elements matched
|
||||
*/
|
||||
JSAPI.prototype.querySelectorAll = function (selectors) {
|
||||
var matchedEls = selectAll(selectors, this, cssSelectOpts);
|
||||
|
||||
return matchedEls.length > 0 ? matchedEls : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Evaluate a string of CSS selectors against the element and returns only the first matched element.
|
||||
*
|
||||
* @param {String} selectors CSS selector(s) string
|
||||
* @return {Array} null if no element matched
|
||||
*/
|
||||
JSAPI.prototype.querySelector = function (selectors) {
|
||||
return selectOne(selectors, this, cssSelectOpts);
|
||||
};
|
||||
|
||||
/**
|
||||
* Test if a selector matches a given element.
|
||||
*
|
||||
* @param {String} selector CSS selector string
|
||||
* @return {Boolean} true if element would be selected by selector string, false if it does not
|
||||
*/
|
||||
JSAPI.prototype.matches = function (selector) {
|
||||
return is(this, selector, cssSelectOpts);
|
||||
};
|
||||
|
||||
165
node_modules/svgo/lib/svgo/plugins.js
generated
vendored
165
node_modules/svgo/lib/svgo/plugins.js
generated
vendored
@@ -1,98 +1,109 @@
|
||||
'use strict';
|
||||
|
||||
const { visit } = require('../xast.js');
|
||||
|
||||
/**
|
||||
* Plugins engine.
|
||||
*
|
||||
* @module plugins
|
||||
*
|
||||
* @param {Object} data input data
|
||||
* @param {Object} plugins plugins object from config
|
||||
* @return {Object} output data
|
||||
* @param {Object} ast input ast
|
||||
* @param {Object} info extra information
|
||||
* @param {Array} plugins plugins object from config
|
||||
* @return {Object} output ast
|
||||
*/
|
||||
module.exports = function(data, plugins) {
|
||||
const invokePlugins = (ast, info, plugins, overrides, globalOverrides) => {
|
||||
for (const plugin of plugins) {
|
||||
const override = overrides == null ? null : overrides[plugin.name];
|
||||
if (override === false) {
|
||||
continue;
|
||||
}
|
||||
const params = { ...plugin.params, ...globalOverrides, ...override };
|
||||
|
||||
plugins.forEach(function(group) {
|
||||
|
||||
switch(group[0].type) {
|
||||
case 'perItem':
|
||||
data = perItem(data, group);
|
||||
break;
|
||||
case 'perItemReverse':
|
||||
data = perItem(data, group, true);
|
||||
break;
|
||||
case 'full':
|
||||
data = full(data, group);
|
||||
break;
|
||||
if (plugin.type === 'perItem') {
|
||||
ast = perItem(ast, info, plugin, params);
|
||||
}
|
||||
if (plugin.type === 'perItemReverse') {
|
||||
ast = perItem(ast, info, plugin, params, true);
|
||||
}
|
||||
if (plugin.type === 'full') {
|
||||
if (plugin.active) {
|
||||
ast = plugin.fn(ast, params, info);
|
||||
}
|
||||
}
|
||||
if (plugin.type === 'visitor') {
|
||||
if (plugin.active) {
|
||||
const visitor = plugin.fn(ast, params, info);
|
||||
if (visitor != null) {
|
||||
visit(ast, visitor);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return ast;
|
||||
};
|
||||
exports.invokePlugins = invokePlugins;
|
||||
|
||||
/**
|
||||
* Direct or reverse per-item loop.
|
||||
*
|
||||
* @param {Object} data input data
|
||||
* @param {Object} info extra information
|
||||
* @param {Array} plugins plugins list to process
|
||||
* @param {Boolean} [reverse] reverse pass?
|
||||
* @param {boolean} [reverse] reverse pass?
|
||||
* @return {Object} output data
|
||||
*/
|
||||
function perItem(data, plugins, reverse) {
|
||||
|
||||
function monkeys(items) {
|
||||
|
||||
items.content = items.content.filter(function(item) {
|
||||
|
||||
// reverse pass
|
||||
if (reverse && item.content) {
|
||||
monkeys(item);
|
||||
}
|
||||
|
||||
// main filter
|
||||
var filter = true;
|
||||
|
||||
for (var i = 0; filter && i < plugins.length; i++) {
|
||||
var plugin = plugins[i];
|
||||
|
||||
if (plugin.active && plugin.fn(item, plugin.params) === false) {
|
||||
filter = false;
|
||||
}
|
||||
}
|
||||
|
||||
// direct pass
|
||||
if (!reverse && item.content) {
|
||||
monkeys(item);
|
||||
}
|
||||
|
||||
return filter;
|
||||
|
||||
});
|
||||
|
||||
return items;
|
||||
|
||||
}
|
||||
|
||||
return monkeys(data);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* "Full" plugins.
|
||||
*
|
||||
* @param {Object} data input data
|
||||
* @param {Array} plugins plugins list to process
|
||||
* @return {Object} output data
|
||||
*/
|
||||
function full(data, plugins) {
|
||||
|
||||
plugins.forEach(function(plugin) {
|
||||
if (plugin.active) {
|
||||
data = plugin.fn(data, plugin.params);
|
||||
}
|
||||
function perItem(data, info, plugin, params, reverse) {
|
||||
function monkeys(items) {
|
||||
items.children = items.children.filter(function (item) {
|
||||
// reverse pass
|
||||
if (reverse && item.children) {
|
||||
monkeys(item);
|
||||
}
|
||||
// main filter
|
||||
let kept = true;
|
||||
if (plugin.active) {
|
||||
kept = plugin.fn(item, params, info) !== false;
|
||||
}
|
||||
// direct pass
|
||||
if (!reverse && item.children) {
|
||||
monkeys(item);
|
||||
}
|
||||
return kept;
|
||||
});
|
||||
|
||||
return data;
|
||||
|
||||
return items;
|
||||
}
|
||||
return monkeys(data);
|
||||
}
|
||||
|
||||
const createPreset = ({ name, plugins }) => {
|
||||
return {
|
||||
name,
|
||||
type: 'full',
|
||||
fn: (ast, params, info) => {
|
||||
const { floatPrecision, overrides } = params;
|
||||
const globalOverrides = {};
|
||||
if (floatPrecision != null) {
|
||||
globalOverrides.floatPrecision = floatPrecision;
|
||||
}
|
||||
if (overrides) {
|
||||
for (const [pluginName, override] of Object.entries(overrides)) {
|
||||
if (override === true) {
|
||||
console.warn(
|
||||
`You are trying to enable ${pluginName} which is not part of preset.\n` +
|
||||
`Try to put it before or after preset, for example\n\n` +
|
||||
`plugins: [\n` +
|
||||
` {\n` +
|
||||
` name: 'preset-default',\n` +
|
||||
` },\n` +
|
||||
` 'cleanupListOfValues'\n` +
|
||||
`]\n`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return invokePlugins(ast, info, plugins, overrides, globalOverrides);
|
||||
},
|
||||
};
|
||||
};
|
||||
exports.createPreset = createPreset;
|
||||
|
||||
187
node_modules/svgo/lib/svgo/svg2js.js
generated
vendored
187
node_modules/svgo/lib/svgo/svg2js.js
generated
vendored
@@ -1,187 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var SAX = require('sax'),
|
||||
JSAPI = require('./jsAPI.js'),
|
||||
entityDeclaration = /<!ENTITY\s+(\S+)\s+(?:'([^\']+)'|"([^\"]+)")\s*>/g;
|
||||
|
||||
var config = {
|
||||
strict: true,
|
||||
trim: false,
|
||||
normalize: true,
|
||||
lowercase: true,
|
||||
xmlns: true,
|
||||
position: true
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert SVG (XML) string to SVG-as-JS object.
|
||||
*
|
||||
* @param {String} data input data
|
||||
* @param {Function} callback
|
||||
*/
|
||||
module.exports = function(data, callback) {
|
||||
|
||||
var sax = SAX.parser(config.strict, config),
|
||||
root = new JSAPI({ elem: '#document' }),
|
||||
current = root,
|
||||
stack = [root],
|
||||
textContext = null,
|
||||
parsingError = false;
|
||||
|
||||
function pushToContent(content) {
|
||||
|
||||
content = new JSAPI(content, current);
|
||||
|
||||
(current.content = current.content || []).push(content);
|
||||
|
||||
return content;
|
||||
|
||||
}
|
||||
|
||||
sax.ondoctype = function(doctype) {
|
||||
|
||||
pushToContent({
|
||||
doctype: doctype
|
||||
});
|
||||
|
||||
var subsetStart = doctype.indexOf('['),
|
||||
entityMatch;
|
||||
|
||||
if (subsetStart >= 0) {
|
||||
entityDeclaration.lastIndex = subsetStart;
|
||||
|
||||
while ((entityMatch = entityDeclaration.exec(data)) != null) {
|
||||
sax.ENTITIES[entityMatch[1]] = entityMatch[2] || entityMatch[3];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
sax.onprocessinginstruction = function(data) {
|
||||
|
||||
pushToContent({
|
||||
processinginstruction: data
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
sax.oncomment = function(comment) {
|
||||
|
||||
pushToContent({
|
||||
comment: comment.trim()
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
sax.oncdata = function(cdata) {
|
||||
|
||||
pushToContent({
|
||||
cdata: cdata
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
sax.onopentag = function(data) {
|
||||
|
||||
var elem = {
|
||||
elem: data.name,
|
||||
prefix: data.prefix,
|
||||
local: data.local
|
||||
};
|
||||
|
||||
if (Object.keys(data.attributes).length) {
|
||||
elem.attrs = {};
|
||||
|
||||
for (var name in data.attributes) {
|
||||
elem.attrs[name] = {
|
||||
name: name,
|
||||
value: data.attributes[name].value,
|
||||
prefix: data.attributes[name].prefix,
|
||||
local: data.attributes[name].local
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
elem = pushToContent(elem);
|
||||
current = elem;
|
||||
|
||||
// Save info about <text> tag to prevent trimming of meaningful whitespace
|
||||
if (data.name == 'text' && !data.prefix) {
|
||||
textContext = current;
|
||||
}
|
||||
|
||||
stack.push(elem);
|
||||
|
||||
};
|
||||
|
||||
sax.ontext = function(text) {
|
||||
|
||||
if (/\S/.test(text) || textContext) {
|
||||
|
||||
if (!textContext)
|
||||
text = text.trim();
|
||||
|
||||
pushToContent({
|
||||
text: text
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
sax.onclosetag = function() {
|
||||
|
||||
var last = stack.pop();
|
||||
|
||||
// Trim text inside <text> tag.
|
||||
if (last == textContext) {
|
||||
trim(textContext);
|
||||
textContext = null;
|
||||
}
|
||||
current = stack[stack.length - 1];
|
||||
|
||||
};
|
||||
|
||||
sax.onerror = function(e) {
|
||||
|
||||
e.message = 'Error in parsing SVG: ' + e.message;
|
||||
if (e.message.indexOf('Unexpected end') < 0) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
sax.onend = function() {
|
||||
|
||||
if (!this.error) {
|
||||
callback(root);
|
||||
} else {
|
||||
callback({ error: this.error.message });
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
try {
|
||||
sax.write(data);
|
||||
} catch (e) {
|
||||
callback({ error: e.message });
|
||||
parsingError = true;
|
||||
}
|
||||
if (!parsingError) sax.close();
|
||||
|
||||
function trim(elem) {
|
||||
if (!elem.content) return elem;
|
||||
|
||||
var start = elem.content[0],
|
||||
end = elem.content[elem.content.length - 1];
|
||||
|
||||
while (start && start.content && !start.text) start = start.content[0];
|
||||
if (start && start.text) start.text = start.text.replace(/^\s+/, '');
|
||||
|
||||
while (end && end.content && !end.text) end = end.content[end.content.length - 1];
|
||||
if (end && end.text) end.text = end.text.replace(/\s+$/, '');
|
||||
|
||||
return elem;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
203
node_modules/svgo/lib/svgo/tools.js
generated
vendored
203
node_modules/svgo/lib/svgo/tools.js
generated
vendored
@@ -1,123 +1,116 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('../types').PathDataCommand} PathDataCommand
|
||||
*/
|
||||
|
||||
/**
|
||||
* Encode plain SVG data string into Data URI string.
|
||||
*
|
||||
* @param {String} str input string
|
||||
* @param {String} type Data URI type
|
||||
* @return {String} output string
|
||||
* @type {(str: string, type?: 'base64' | 'enc' | 'unenc') => string}
|
||||
*/
|
||||
exports.encodeSVGDatauri = function(str, type) {
|
||||
|
||||
var prefix = 'data:image/svg+xml';
|
||||
|
||||
exports.encodeSVGDatauri = (str, type) => {
|
||||
var prefix = 'data:image/svg+xml';
|
||||
if (!type || type === 'base64') {
|
||||
// base64
|
||||
if (!type || type === 'base64') {
|
||||
|
||||
prefix += ';base64,';
|
||||
|
||||
str = prefix + new Buffer(str).toString('base64');
|
||||
|
||||
prefix += ';base64,';
|
||||
str = prefix + Buffer.from(str).toString('base64');
|
||||
} else if (type === 'enc') {
|
||||
// URI encoded
|
||||
} else if (type === 'enc') {
|
||||
|
||||
str = prefix + ',' + encodeURIComponent(str);
|
||||
|
||||
str = prefix + ',' + encodeURIComponent(str);
|
||||
} else if (type === 'unenc') {
|
||||
// unencoded
|
||||
} else if (type === 'unenc') {
|
||||
|
||||
str = prefix + ',' + str;
|
||||
|
||||
}
|
||||
|
||||
return str;
|
||||
|
||||
str = prefix + ',' + str;
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode SVG Data URI string into plain SVG string.
|
||||
*
|
||||
* @param {string} str input string
|
||||
* @return {String} output string
|
||||
* @type {(str: string) => string}
|
||||
*/
|
||||
exports.decodeSVGDatauri = function(str) {
|
||||
var regexp = /data:image\/svg\+xml(;charset=[^;,]*)?(;base64)?,(.*)/;
|
||||
var match = regexp.exec(str);
|
||||
exports.decodeSVGDatauri = (str) => {
|
||||
var regexp = /data:image\/svg\+xml(;charset=[^;,]*)?(;base64)?,(.*)/;
|
||||
var match = regexp.exec(str);
|
||||
|
||||
// plain string
|
||||
if (!match) return str;
|
||||
// plain string
|
||||
if (!match) return str;
|
||||
|
||||
var data = match[3];
|
||||
var data = match[3];
|
||||
|
||||
if (match[2]) {
|
||||
// base64
|
||||
if (match[2]) {
|
||||
|
||||
str = new Buffer(data, 'base64').toString('utf8');
|
||||
|
||||
str = Buffer.from(data, 'base64').toString('utf8');
|
||||
} else if (data.charAt(0) === '%') {
|
||||
// URI encoded
|
||||
} else if (data.charAt(0) === '%') {
|
||||
|
||||
str = decodeURIComponent(data);
|
||||
|
||||
str = decodeURIComponent(data);
|
||||
} else if (data.charAt(0) === '<') {
|
||||
// unencoded
|
||||
} else if (data.charAt(0) === '<') {
|
||||
str = data;
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
str = data;
|
||||
/**
|
||||
* @typedef {{
|
||||
* noSpaceAfterFlags?: boolean,
|
||||
* leadingZero?: boolean,
|
||||
* negativeExtraSpace?: boolean
|
||||
* }} CleanupOutDataParams
|
||||
*/
|
||||
|
||||
/**
|
||||
* Convert a row of numbers to an optimized string view.
|
||||
*
|
||||
* @example
|
||||
* [0, -1, .5, .5] → "0-1 .5.5"
|
||||
*
|
||||
* @type {(data: Array<number>, params: CleanupOutDataParams, command?: PathDataCommand) => string}
|
||||
*/
|
||||
exports.cleanupOutData = (data, params, command) => {
|
||||
let str = '';
|
||||
let delimiter;
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
let prev;
|
||||
|
||||
data.forEach((item, i) => {
|
||||
// space delimiter by default
|
||||
delimiter = ' ';
|
||||
|
||||
// no extra space in front of first number
|
||||
if (i == 0) delimiter = '';
|
||||
|
||||
// no extra space after 'arcto' command flags(large-arc and sweep flags)
|
||||
// a20 60 45 0 1 30 20 → a20 60 45 0130 20
|
||||
if (params.noSpaceAfterFlags && (command == 'A' || command == 'a')) {
|
||||
var pos = i % 7;
|
||||
if (pos == 4 || pos == 5) delimiter = '';
|
||||
}
|
||||
|
||||
return str;
|
||||
};
|
||||
|
||||
exports.intersectArrays = function(a, b) {
|
||||
return a.filter(function(n) {
|
||||
return b.indexOf(n) > -1;
|
||||
});
|
||||
};
|
||||
|
||||
exports.cleanupOutData = function(data, params) {
|
||||
|
||||
var str = '',
|
||||
delimiter,
|
||||
prev;
|
||||
|
||||
data.forEach(function(item, i) {
|
||||
|
||||
// space delimiter by default
|
||||
delimiter = ' ';
|
||||
|
||||
// no extra space in front of first number
|
||||
if (i === 0) {
|
||||
delimiter = '';
|
||||
}
|
||||
|
||||
// remove floating-point numbers leading zeros
|
||||
// 0.5 → .5
|
||||
// -0.5 → -.5
|
||||
if (params.leadingZero) {
|
||||
item = removeLeadingZero(item);
|
||||
}
|
||||
|
||||
// no extra space in front of negative number or
|
||||
// in front of a floating number if a previous number is floating too
|
||||
if (
|
||||
params.negativeExtraSpace &&
|
||||
(item < 0 ||
|
||||
(/^\./.test(item) && prev % 1 !== 0)
|
||||
)
|
||||
) {
|
||||
delimiter = '';
|
||||
}
|
||||
|
||||
// save prev item value
|
||||
prev = item;
|
||||
|
||||
str += delimiter + item;
|
||||
|
||||
});
|
||||
|
||||
return str;
|
||||
// remove floating-point numbers leading zeros
|
||||
// 0.5 → .5
|
||||
// -0.5 → -.5
|
||||
const itemStr = params.leadingZero
|
||||
? removeLeadingZero(item)
|
||||
: item.toString();
|
||||
|
||||
// no extra space in front of negative number or
|
||||
// in front of a floating number if a previous number is floating too
|
||||
if (
|
||||
params.negativeExtraSpace &&
|
||||
delimiter != '' &&
|
||||
(item < 0 || (itemStr.charAt(0) === '.' && prev % 1 !== 0))
|
||||
) {
|
||||
delimiter = '';
|
||||
}
|
||||
// save prev item value
|
||||
prev = item;
|
||||
str += delimiter + itemStr;
|
||||
});
|
||||
return str;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -129,18 +122,16 @@ exports.cleanupOutData = function(data, params) {
|
||||
* @example
|
||||
* -0.5 → -.5
|
||||
*
|
||||
* @param {Float} num input number
|
||||
*
|
||||
* @return {String} output number as string
|
||||
* @type {(num: number) => string}
|
||||
*/
|
||||
var removeLeadingZero = exports.removeLeadingZero = function(num) {
|
||||
|
||||
if (num > 0 && num < 1) {
|
||||
num = ('' + num).slice(1);
|
||||
} else if (num < 0 && num > -1) {
|
||||
num = '-' + ('' + num).slice(2);
|
||||
}
|
||||
|
||||
return num;
|
||||
const removeLeadingZero = (num) => {
|
||||
var strNum = num.toString();
|
||||
|
||||
if (0 < num && num < 1 && strNum.charAt(0) === '0') {
|
||||
strNum = strNum.slice(1);
|
||||
} else if (-1 < num && num < 0 && strNum.charAt(1) === '0') {
|
||||
strNum = strNum.charAt(0) + strNum.slice(2);
|
||||
}
|
||||
return strNum;
|
||||
};
|
||||
exports.removeLeadingZero = removeLeadingZero;
|
||||
|
||||
172
node_modules/svgo/lib/types.ts
generated
vendored
Normal file
172
node_modules/svgo/lib/types.ts
generated
vendored
Normal file
@@ -0,0 +1,172 @@
|
||||
export type XastDoctype = {
|
||||
type: 'doctype';
|
||||
name: string;
|
||||
data: {
|
||||
doctype: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type XastInstruction = {
|
||||
type: 'instruction';
|
||||
name: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type XastComment = {
|
||||
type: 'comment';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type XastCdata = {
|
||||
type: 'cdata';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type XastText = {
|
||||
type: 'text';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type XastElement = {
|
||||
type: 'element';
|
||||
name: string;
|
||||
attributes: Record<string, string>;
|
||||
children: Array<XastChild>;
|
||||
};
|
||||
|
||||
export type XastChild =
|
||||
| XastDoctype
|
||||
| XastInstruction
|
||||
| XastComment
|
||||
| XastCdata
|
||||
| XastText
|
||||
| XastElement;
|
||||
|
||||
export type XastRoot = {
|
||||
type: 'root';
|
||||
children: Array<XastChild>;
|
||||
};
|
||||
|
||||
export type XastParent = XastRoot | XastElement;
|
||||
|
||||
export type XastNode = XastRoot | XastChild;
|
||||
|
||||
export type StringifyOptions = {
|
||||
doctypeStart?: string;
|
||||
doctypeEnd?: string;
|
||||
procInstStart?: string;
|
||||
procInstEnd?: string;
|
||||
tagOpenStart?: string;
|
||||
tagOpenEnd?: string;
|
||||
tagCloseStart?: string;
|
||||
tagCloseEnd?: string;
|
||||
tagShortStart?: string;
|
||||
tagShortEnd?: string;
|
||||
attrStart?: string;
|
||||
attrEnd?: string;
|
||||
commentStart?: string;
|
||||
commentEnd?: string;
|
||||
cdataStart?: string;
|
||||
cdataEnd?: string;
|
||||
textStart?: string;
|
||||
textEnd?: string;
|
||||
indent?: number | string;
|
||||
regEntities?: RegExp;
|
||||
regValEntities?: RegExp;
|
||||
encodeEntity?: (char: string) => string;
|
||||
pretty?: boolean;
|
||||
useShortTags?: boolean;
|
||||
eol?: 'lf' | 'crlf';
|
||||
finalNewline?: boolean;
|
||||
};
|
||||
|
||||
type VisitorNode<Node> = {
|
||||
enter?: (node: Node, parentNode: XastParent) => void | symbol;
|
||||
exit?: (node: Node, parentNode: XastParent) => void;
|
||||
};
|
||||
|
||||
type VisitorRoot = {
|
||||
enter?: (node: XastRoot, parentNode: null) => void;
|
||||
exit?: (node: XastRoot, parentNode: null) => void;
|
||||
};
|
||||
|
||||
export type Visitor = {
|
||||
doctype?: VisitorNode<XastDoctype>;
|
||||
instruction?: VisitorNode<XastInstruction>;
|
||||
comment?: VisitorNode<XastComment>;
|
||||
cdata?: VisitorNode<XastCdata>;
|
||||
text?: VisitorNode<XastText>;
|
||||
element?: VisitorNode<XastElement>;
|
||||
root?: VisitorRoot;
|
||||
};
|
||||
|
||||
export type PluginInfo = {
|
||||
path?: string;
|
||||
multipassCount: number;
|
||||
};
|
||||
|
||||
export type Plugin<Params> = (
|
||||
root: XastRoot,
|
||||
params: Params,
|
||||
info: PluginInfo
|
||||
) => null | Visitor;
|
||||
|
||||
export type Specificity = [number, number, number, number];
|
||||
|
||||
export type StylesheetDeclaration = {
|
||||
name: string;
|
||||
value: string;
|
||||
important: boolean;
|
||||
};
|
||||
|
||||
export type StylesheetRule = {
|
||||
dynamic: boolean;
|
||||
selectors: string;
|
||||
specificity: Specificity;
|
||||
declarations: Array<StylesheetDeclaration>;
|
||||
};
|
||||
|
||||
export type Stylesheet = {
|
||||
rules: Array<StylesheetRule>;
|
||||
parents: Map<XastElement, XastParent>;
|
||||
};
|
||||
|
||||
type StaticStyle = {
|
||||
type: 'static';
|
||||
inherited: boolean;
|
||||
value: string;
|
||||
};
|
||||
|
||||
type DynamicStyle = {
|
||||
type: 'dynamic';
|
||||
inherited: boolean;
|
||||
};
|
||||
|
||||
export type ComputedStyles = Record<string, StaticStyle | DynamicStyle>;
|
||||
|
||||
export type PathDataCommand =
|
||||
| 'M'
|
||||
| 'm'
|
||||
| 'Z'
|
||||
| 'z'
|
||||
| 'L'
|
||||
| 'l'
|
||||
| 'H'
|
||||
| 'h'
|
||||
| 'V'
|
||||
| 'v'
|
||||
| 'C'
|
||||
| 'c'
|
||||
| 'S'
|
||||
| 's'
|
||||
| 'Q'
|
||||
| 'q'
|
||||
| 'T'
|
||||
| 't'
|
||||
| 'A'
|
||||
| 'a';
|
||||
|
||||
export type PathDataItem = {
|
||||
command: PathDataCommand;
|
||||
args: Array<number>;
|
||||
};
|
||||
102
node_modules/svgo/lib/xast.js
generated
vendored
Normal file
102
node_modules/svgo/lib/xast.js
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('./types').XastNode} XastNode
|
||||
* @typedef {import('./types').XastChild} XastChild
|
||||
* @typedef {import('./types').XastParent} XastParent
|
||||
* @typedef {import('./types').Visitor} Visitor
|
||||
*/
|
||||
|
||||
const { selectAll, selectOne, is } = require('css-select');
|
||||
const xastAdaptor = require('./svgo/css-select-adapter.js');
|
||||
|
||||
const cssSelectOptions = {
|
||||
xmlMode: true,
|
||||
adapter: xastAdaptor,
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(node: XastNode, selector: string) => Array<XastChild>}
|
||||
*/
|
||||
const querySelectorAll = (node, selector) => {
|
||||
return selectAll(selector, node, cssSelectOptions);
|
||||
};
|
||||
exports.querySelectorAll = querySelectorAll;
|
||||
|
||||
/**
|
||||
* @type {(node: XastNode, selector: string) => null | XastChild}
|
||||
*/
|
||||
const querySelector = (node, selector) => {
|
||||
return selectOne(selector, node, cssSelectOptions);
|
||||
};
|
||||
exports.querySelector = querySelector;
|
||||
|
||||
/**
|
||||
* @type {(node: XastChild, selector: string) => boolean}
|
||||
*/
|
||||
const matches = (node, selector) => {
|
||||
return is(node, selector, cssSelectOptions);
|
||||
};
|
||||
exports.matches = matches;
|
||||
|
||||
/**
|
||||
* @type {(node: XastChild, name: string) => null | XastChild}
|
||||
*/
|
||||
const closestByName = (node, name) => {
|
||||
let currentNode = node;
|
||||
while (currentNode) {
|
||||
if (currentNode.type === 'element' && currentNode.name === name) {
|
||||
return currentNode;
|
||||
}
|
||||
// @ts-ignore parentNode is hidden from public usage
|
||||
currentNode = currentNode.parentNode;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
exports.closestByName = closestByName;
|
||||
|
||||
const visitSkip = Symbol();
|
||||
exports.visitSkip = visitSkip;
|
||||
|
||||
/**
|
||||
* @type {(node: XastNode, visitor: Visitor, parentNode?: any) => void}
|
||||
*/
|
||||
const visit = (node, visitor, parentNode) => {
|
||||
const callbacks = visitor[node.type];
|
||||
if (callbacks && callbacks.enter) {
|
||||
// @ts-ignore hard to infer
|
||||
const symbol = callbacks.enter(node, parentNode);
|
||||
if (symbol === visitSkip) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// visit root children
|
||||
if (node.type === 'root') {
|
||||
// copy children array to not loose cursor when children is spliced
|
||||
for (const child of node.children) {
|
||||
visit(child, visitor, node);
|
||||
}
|
||||
}
|
||||
// visit element children if still attached to parent
|
||||
if (node.type === 'element') {
|
||||
if (parentNode.children.includes(node)) {
|
||||
for (const child of node.children) {
|
||||
visit(child, visitor, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (callbacks && callbacks.exit) {
|
||||
// @ts-ignore hard to infer
|
||||
callbacks.exit(node, parentNode);
|
||||
}
|
||||
};
|
||||
exports.visit = visit;
|
||||
|
||||
/**
|
||||
* @type {(node: XastChild, parentNode: XastParent) => void}
|
||||
*/
|
||||
const detachNodeFromParent = (node, parentNode) => {
|
||||
// avoid splice to not break for loops
|
||||
parentNode.children = parentNode.children.filter((child) => child !== node);
|
||||
};
|
||||
exports.detachNodeFromParent = detachNodeFromParent;
|
||||
440
node_modules/svgo/node_modules/commander/CHANGELOG.md
generated
vendored
Normal file
440
node_modules/svgo/node_modules/commander/CHANGELOG.md
generated
vendored
Normal file
@@ -0,0 +1,440 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
|
||||
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.)
|
||||
|
||||
<!-- markdownlint-disable MD024 -->
|
||||
<!-- markdownlint-disable MD004 -->
|
||||
|
||||
## [7.2.0] (2021-03-26)
|
||||
|
||||
### Added
|
||||
|
||||
- TypeScript typing for `parent` property on `Command` ([#1475])
|
||||
- TypeScript typing for `.attributeName()` on `Option` ([#1483])
|
||||
- support information in package ([#1477])
|
||||
|
||||
### Changed
|
||||
|
||||
- improvements to error messages, README, and tests
|
||||
- update dependencies
|
||||
|
||||
## [7.1.0] (2021-02-15)
|
||||
|
||||
### Added
|
||||
|
||||
- support for named imports from ECMAScript modules ([#1440])
|
||||
- add `.cjs` to list of expected script file extensions ([#1449])
|
||||
- allow using option choices and variadic together ([#1454])
|
||||
|
||||
### Fixed
|
||||
|
||||
- replace use of deprecated `process.mainModule` ([#1448])
|
||||
- regression for legacy `command('*')` and call when command line includes options ([#1464])
|
||||
- regression for `on('command:*', ...)` and call when command line includes unknown options ([#1464])
|
||||
- display best error for combination of unknown command and unknown option (i.e. unknown command) ([#1464])
|
||||
|
||||
### Changed
|
||||
|
||||
- make TypeScript typings tests stricter ([#1453])
|
||||
- improvements to README and tests
|
||||
|
||||
## [7.0.0] (2021-01-15)
|
||||
|
||||
### Added
|
||||
|
||||
- `.enablePositionalOptions()` to let program and subcommand reuse same option ([#1427])
|
||||
- `.passThroughOptions()` to pass options through to other programs without needing `--` ([#1427])
|
||||
- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409])
|
||||
- `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387])
|
||||
- use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296])
|
||||
- enhance Option class ([#1331])
|
||||
- allow hiding options from help
|
||||
- allow restricting option arguments to a list of choices
|
||||
- allow setting how default value is shown in help
|
||||
- `.createOption()` to support subclassing of automatically created options (like `.createCommand()`) ([#1380])
|
||||
- refactor the code generating the help into a separate public Help class ([#1365])
|
||||
- support sorting subcommands and options in help
|
||||
- support specifying wrap width (columns)
|
||||
- allow subclassing Help class
|
||||
- allow configuring Help class without subclassing
|
||||
|
||||
### Changed
|
||||
|
||||
- *Breaking:* options are stored safely by default, not as properties on the command ([#1409])
|
||||
- this especially affects accessing options on program, use `program.opts()`
|
||||
- revert behaviour with `.storeOptionsAsProperties()`
|
||||
- *Breaking:* action handlers are passed options and command separately ([#1409])
|
||||
- deprecated callback parameter to `.help()` and `.outputHelp()` (removed from README) ([#1296])
|
||||
- *Breaking:* errors now displayed using `process.stderr.write()` instead of `console.error()`
|
||||
- deprecate `.on('--help')` (removed from README) ([#1296])
|
||||
- initialise the command description to empty string (previously undefined) ([#1365])
|
||||
- document and annotate deprecated routines ([#1349])
|
||||
|
||||
### Fixed
|
||||
|
||||
- wrapping bugs in help ([#1365])
|
||||
- first line of command description was wrapping two characters early
|
||||
- pad width calculation was not including help option and help command
|
||||
- pad width calculation was including hidden options and commands
|
||||
- improve backwards compatibility for custom command event listeners ([#1403])
|
||||
|
||||
### Deleted
|
||||
|
||||
- *Breaking:* `.passCommandToAction()` ([#1409])
|
||||
- no longer needed as action handler is passed options and command
|
||||
- *Breaking:* "extra arguments" parameter to action handler ([#1409])
|
||||
- if being used to detect excess arguments, there is now an error available by setting `.allowExcessArguments(false)`
|
||||
|
||||
### Migration Tips
|
||||
|
||||
The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.
|
||||
|
||||
If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`.
|
||||
To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_,
|
||||
to match the new "options" and "command" parameters (see below).
|
||||
|
||||
**program options**
|
||||
|
||||
Use the `.opts()` method to access the options. This is available on any command but is used most with the program.
|
||||
|
||||
```js
|
||||
program.option('-d, --debug');
|
||||
program.parse();
|
||||
// Old code before Commander 7
|
||||
if (program.debug) console.log(`Program name is ${program.name()}`);
|
||||
```
|
||||
|
||||
```js
|
||||
// New code
|
||||
const options = program.opts();
|
||||
if (options.debug) console.log(`Program name is ${program.name()}`);
|
||||
```
|
||||
|
||||
**action handler**
|
||||
|
||||
The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you
|
||||
only accessed the options there may be no code changes required.
|
||||
|
||||
```js
|
||||
program
|
||||
.command('compress <filename>')
|
||||
.option('-t, --trace')
|
||||
// Old code before Commander 7
|
||||
.action((filename, cmd)) => {
|
||||
if (cmd.trace) console.log(`Command name is ${cmd.name()}`);
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
// New code
|
||||
.action((filename, options, command)) => {
|
||||
if (options.trace) console.log(`Command name is ${command.name()}`);
|
||||
});
|
||||
```
|
||||
|
||||
If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code.
|
||||
|
||||
```js
|
||||
program
|
||||
.command('compress <filename>')
|
||||
.storeOptionsAsProperties(false)
|
||||
.option('-t, --trace')
|
||||
// Old code before Commander 7
|
||||
.action((filename, command)) => {
|
||||
if (command.opts().trace) console.log(`Command name is ${command.name()}`);
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
// New code
|
||||
.action((filename, options, command)) => {
|
||||
if (command.opts().trace) console.log(`Command name is ${command.name()}`);
|
||||
});
|
||||
```
|
||||
|
||||
## [7.0.0-2] (2020-12-14)
|
||||
|
||||
(Released in 7.0.0)
|
||||
|
||||
## [7.0.0-1] (2020-11-21)
|
||||
|
||||
(Released in 7.0.0)
|
||||
|
||||
## [7.0.0-0] (2020-10-25)
|
||||
|
||||
(Released in 7.0.0)
|
||||
|
||||
## [6.2.1] (2020-12-13)
|
||||
|
||||
### Fixed
|
||||
|
||||
- some tests failed if directory path included a space ([1390])
|
||||
|
||||
## [6.2.0] (2020-10-25)
|
||||
|
||||
### Added
|
||||
|
||||
- added 'tsx' file extension for stand-alone executable subcommands ([#1368])
|
||||
- documented second parameter to `.description()` to describe command arguments ([#1353])
|
||||
- documentation of special cases with options taking varying numbers of option-arguments ([#1332])
|
||||
- documentation for terminology ([#1361])
|
||||
|
||||
### Fixed
|
||||
|
||||
- add missing TypeScript definition for `.addHelpCommand()' ([#1375])
|
||||
- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360])
|
||||
|
||||
### Changed
|
||||
|
||||
- update dependencies
|
||||
|
||||
## [6.1.0] (2020-08-28)
|
||||
|
||||
### Added
|
||||
|
||||
- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306])
|
||||
- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326])
|
||||
- allow disabling the built-in help option using `.helpOption(false)` ([#1325])
|
||||
- allow just some arguments in `argumentDescription` to `.description()` ([#1323])
|
||||
|
||||
### Changed
|
||||
|
||||
- tidy async test and remove lint override ([#1312])
|
||||
|
||||
### Fixed
|
||||
|
||||
- executable subcommand launching when script path not known ([#1322])
|
||||
|
||||
## [6.0.0] (2020-07-21)
|
||||
|
||||
### Added
|
||||
|
||||
- add support for variadic options ([#1250])
|
||||
- allow options to be added with just a short flag ([#1256])
|
||||
- *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase)
|
||||
- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275])
|
||||
|
||||
### Fixed
|
||||
|
||||
- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301])
|
||||
|
||||
## [6.0.0-0] (2020-06-20)
|
||||
|
||||
(Released in 6.0.0)
|
||||
|
||||
## [5.1.0] (2020-04-25)
|
||||
|
||||
### Added
|
||||
|
||||
- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236])
|
||||
- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232])
|
||||
|
||||
### Fixed
|
||||
|
||||
- omit masked help flags from the displayed help ([#645], [#1247])
|
||||
- remove old short help flag when change help flags using `helpOption` ([#1248])
|
||||
|
||||
### Changed
|
||||
|
||||
- remove use of `arguments` to improve auto-generated help in editors ([#1235])
|
||||
- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232])
|
||||
- improvements to documentation
|
||||
- update dependencies
|
||||
- update tested versions of node
|
||||
- eliminate lint errors in TypeScript ([#1208])
|
||||
|
||||
## [5.0.0] (2020-03-14)
|
||||
|
||||
### Added
|
||||
|
||||
* support for nested commands with action-handlers ([#1] [#764] [#1149])
|
||||
* `.addCommand()` for adding a separately configured command ([#764] [#1149])
|
||||
* allow a non-executable to be set as the default command ([#742] [#1149])
|
||||
* implicit help command when there are subcommands (previously only if executables) ([#1149])
|
||||
* customise implicit help command with `.addHelpCommand()` ([#1149])
|
||||
* display error message for unknown subcommand, by default ([#432] [#1088] [#1149])
|
||||
* display help for missing subcommand, by default ([#1088] [#1149])
|
||||
* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145])
|
||||
* `.parseOption()` includes short flag and long flag expansions ([#1145])
|
||||
* `.helpInformation()` returns help text as a string, previously a private routine ([#1169])
|
||||
* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172])
|
||||
* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172])
|
||||
* suggest help option along with unknown command error ([#1179])
|
||||
* TypeScript definition for `commands` property of `Command` ([#1184])
|
||||
* export `program` property ([#1195])
|
||||
* `createCommand` factory method to simplify subclassing ([#1191])
|
||||
|
||||
### Fixed
|
||||
|
||||
* preserve argument order in subcommands ([#508] [#962] [#1138])
|
||||
* do not emit `command:*` for executable subcommands ([#809] [#1149])
|
||||
* action handler called whether or not there are non-option arguments ([#1062] [#1149])
|
||||
* combining option short flag and value in single argument now works for subcommands ([#1145])
|
||||
* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149])
|
||||
* implicit help command works with command aliases ([#948] [#1149])
|
||||
* options are validated whether or not there is an action handler ([#1149])
|
||||
|
||||
### Changed
|
||||
|
||||
* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138])
|
||||
* *Breaking* display error if required argument for command is missing ([#995] [#1149])
|
||||
* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119])
|
||||
* *Breaking* `.allowUnknownOption()` ([#802] [#1138])
|
||||
* unknown options included in arguments passed to command action handler
|
||||
* unknown options included in `.args`
|
||||
* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145])
|
||||
* *Breaking* `.parseOptions()` ([#1138])
|
||||
* `args` in returned result renamed `operands` and does not include anything after first unknown option
|
||||
* `unknown` in returned result has arguments after first unknown option including operands, not just options and values
|
||||
* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown ([#1138])
|
||||
* refactor Option from prototype to class ([#1133])
|
||||
* refactor Command from prototype to class ([#1159])
|
||||
* changes to error handling ([#1165])
|
||||
* throw for author error, not just display message
|
||||
* preflight for variadic error
|
||||
* add tips to missing subcommand executable
|
||||
* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180])
|
||||
* `.parseAsync` returns `Promise<this>` to be consistent with `.parse()` ([#1180])
|
||||
* update dependencies
|
||||
|
||||
### Removed
|
||||
|
||||
* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146])
|
||||
* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145])
|
||||
* `parseExpectedArgs` is now private ([#1149])
|
||||
|
||||
### Migration Tips
|
||||
|
||||
If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour.
|
||||
|
||||
If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour.
|
||||
|
||||
If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command.
|
||||
|
||||
If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)`
|
||||
to expand `-fb` to `-f -b` rather than `-f b`.
|
||||
|
||||
## [5.0.0-4] (2020-03-03)
|
||||
|
||||
(Released in 5.0.0)
|
||||
|
||||
## [5.0.0-3] (2020-02-20)
|
||||
|
||||
(Released in 5.0.0)
|
||||
|
||||
## [5.0.0-2] (2020-02-10)
|
||||
|
||||
(Released in 5.0.0)
|
||||
|
||||
## [5.0.0-1] (2020-02-08)
|
||||
|
||||
(Released in 5.0.0)
|
||||
|
||||
## [5.0.0-0] (2020-02-02)
|
||||
|
||||
(Released in 5.0.0)
|
||||
|
||||
## Older versions
|
||||
|
||||
* [4.x](./changelogs/CHANGELOG-4.md)
|
||||
* [3.x](./changelogs/CHANGELOG-3.md)
|
||||
* [2.x](./changelogs/CHANGELOG-2.md)
|
||||
* [1.x](./changelogs/CHANGELOG-1.md)
|
||||
* [0.x](./changelogs/CHANGELOG-0.md)
|
||||
|
||||
[#1]: https://github.com/tj/commander.js/issues/1
|
||||
[#432]: https://github.com/tj/commander.js/issues/432
|
||||
[#508]: https://github.com/tj/commander.js/issues/508
|
||||
[#512]: https://github.com/tj/commander.js/issues/512
|
||||
[#531]: https://github.com/tj/commander.js/issues/531
|
||||
[#645]: https://github.com/tj/commander.js/issues/645
|
||||
[#742]: https://github.com/tj/commander.js/issues/742
|
||||
[#764]: https://github.com/tj/commander.js/issues/764
|
||||
[#802]: https://github.com/tj/commander.js/issues/802
|
||||
[#809]: https://github.com/tj/commander.js/issues/809
|
||||
[#948]: https://github.com/tj/commander.js/issues/948
|
||||
[#962]: https://github.com/tj/commander.js/issues/962
|
||||
[#995]: https://github.com/tj/commander.js/issues/995
|
||||
[#1032]: https://github.com/tj/commander.js/issues/1032
|
||||
[#1062]: https://github.com/tj/commander.js/pull/1062
|
||||
[#1088]: https://github.com/tj/commander.js/issues/1088
|
||||
[#1119]: https://github.com/tj/commander.js/pull/1119
|
||||
[#1133]: https://github.com/tj/commander.js/pull/1133
|
||||
[#1138]: https://github.com/tj/commander.js/pull/1138
|
||||
[#1145]: https://github.com/tj/commander.js/pull/1145
|
||||
[#1146]: https://github.com/tj/commander.js/pull/1146
|
||||
[#1149]: https://github.com/tj/commander.js/pull/1149
|
||||
[#1153]: https://github.com/tj/commander.js/issues/1153
|
||||
[#1159]: https://github.com/tj/commander.js/pull/1159
|
||||
[#1165]: https://github.com/tj/commander.js/pull/1165
|
||||
[#1169]: https://github.com/tj/commander.js/pull/1169
|
||||
[#1172]: https://github.com/tj/commander.js/pull/1172
|
||||
[#1179]: https://github.com/tj/commander.js/pull/1179
|
||||
[#1180]: https://github.com/tj/commander.js/pull/1180
|
||||
[#1184]: https://github.com/tj/commander.js/pull/1184
|
||||
[#1191]: https://github.com/tj/commander.js/pull/1191
|
||||
[#1195]: https://github.com/tj/commander.js/pull/1195
|
||||
[#1208]: https://github.com/tj/commander.js/pull/1208
|
||||
[#1232]: https://github.com/tj/commander.js/pull/1232
|
||||
[#1235]: https://github.com/tj/commander.js/pull/1235
|
||||
[#1236]: https://github.com/tj/commander.js/pull/1236
|
||||
[#1247]: https://github.com/tj/commander.js/pull/1247
|
||||
[#1248]: https://github.com/tj/commander.js/pull/1248
|
||||
[#1250]: https://github.com/tj/commander.js/pull/1250
|
||||
[#1256]: https://github.com/tj/commander.js/pull/1256
|
||||
[#1275]: https://github.com/tj/commander.js/pull/1275
|
||||
[#1296]: https://github.com/tj/commander.js/pull/1296
|
||||
[#1301]: https://github.com/tj/commander.js/issues/1301
|
||||
[#1306]: https://github.com/tj/commander.js/pull/1306
|
||||
[#1312]: https://github.com/tj/commander.js/pull/1312
|
||||
[#1322]: https://github.com/tj/commander.js/pull/1322
|
||||
[#1323]: https://github.com/tj/commander.js/pull/1323
|
||||
[#1325]: https://github.com/tj/commander.js/pull/1325
|
||||
[#1326]: https://github.com/tj/commander.js/pull/1326
|
||||
[#1331]: https://github.com/tj/commander.js/pull/1331
|
||||
[#1332]: https://github.com/tj/commander.js/pull/1332
|
||||
[#1349]: https://github.com/tj/commander.js/pull/1349
|
||||
[#1353]: https://github.com/tj/commander.js/pull/1353
|
||||
[#1360]: https://github.com/tj/commander.js/pull/1360
|
||||
[#1361]: https://github.com/tj/commander.js/pull/1361
|
||||
[#1365]: https://github.com/tj/commander.js/pull/1365
|
||||
[#1368]: https://github.com/tj/commander.js/pull/1368
|
||||
[#1375]: https://github.com/tj/commander.js/pull/1375
|
||||
[#1380]: https://github.com/tj/commander.js/pull/1380
|
||||
[#1387]: https://github.com/tj/commander.js/pull/1387
|
||||
[#1390]: https://github.com/tj/commander.js/pull/1390
|
||||
[#1403]: https://github.com/tj/commander.js/pull/1403
|
||||
[#1409]: https://github.com/tj/commander.js/pull/1409
|
||||
[#1427]: https://github.com/tj/commander.js/pull/1427
|
||||
[#1440]: https://github.com/tj/commander.js/pull/1440
|
||||
[#1448]: https://github.com/tj/commander.js/pull/1448
|
||||
[#1449]: https://github.com/tj/commander.js/pull/1449
|
||||
[#1453]: https://github.com/tj/commander.js/pull/1453
|
||||
[#1454]: https://github.com/tj/commander.js/pull/1454
|
||||
[#1464]: https://github.com/tj/commander.js/pull/1464
|
||||
[#1475]: https://github.com/tj/commander.js/pull/1475
|
||||
[#1477]: https://github.com/tj/commander.js/pull/1477
|
||||
[#1483]: https://github.com/tj/commander.js/pull/1483
|
||||
|
||||
[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
|
||||
[7.2.0]: https://github.com/tj/commander.js/compare/v7.1.0...v7.2.0
|
||||
[7.1.0]: https://github.com/tj/commander.js/compare/v7.0.0...v7.1.0
|
||||
[7.0.0]: https://github.com/tj/commander.js/compare/v6.2.1...v7.0.0
|
||||
[7.0.0-2]: https://github.com/tj/commander.js/compare/v7.0.0-1...v7.0.0-2
|
||||
[7.0.0-1]: https://github.com/tj/commander.js/compare/v7.0.0-0...v7.0.0-1
|
||||
[7.0.0-0]: https://github.com/tj/commander.js/compare/v6.2.0...v7.0.0-0
|
||||
[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1
|
||||
[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0
|
||||
[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0
|
||||
[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0
|
||||
[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0
|
||||
[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0
|
||||
[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0
|
||||
[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4
|
||||
[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3
|
||||
[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2
|
||||
[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1
|
||||
[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0
|
||||
22
node_modules/svgo/node_modules/commander/LICENSE
generated
vendored
Normal file
22
node_modules/svgo/node_modules/commander/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
917
node_modules/svgo/node_modules/commander/Readme.md
generated
vendored
Normal file
917
node_modules/svgo/node_modules/commander/Readme.md
generated
vendored
Normal file
@@ -0,0 +1,917 @@
|
||||
# Commander.js
|
||||
|
||||
[](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
|
||||
[](https://www.npmjs.org/package/commander)
|
||||
[](https://npmcharts.com/compare/commander?minimal=true)
|
||||
[](https://packagephobia.now.sh/result?p=commander)
|
||||
|
||||
The complete solution for [node.js](http://nodejs.org) command-line interfaces.
|
||||
|
||||
Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
|
||||
|
||||
- [Commander.js](#commanderjs)
|
||||
- [Installation](#installation)
|
||||
- [Declaring _program_ variable](#declaring-program-variable)
|
||||
- [Options](#options)
|
||||
- [Common option types, boolean and value](#common-option-types-boolean-and-value)
|
||||
- [Default option value](#default-option-value)
|
||||
- [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
|
||||
- [Required option](#required-option)
|
||||
- [Variadic option](#variadic-option)
|
||||
- [Version option](#version-option)
|
||||
- [More configuration](#more-configuration)
|
||||
- [Custom option processing](#custom-option-processing)
|
||||
- [Commands](#commands)
|
||||
- [Specify the argument syntax](#specify-the-argument-syntax)
|
||||
- [Action handler](#action-handler)
|
||||
- [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
|
||||
- [Automated help](#automated-help)
|
||||
- [Custom help](#custom-help)
|
||||
- [Display help from code](#display-help-from-code)
|
||||
- [.usage and .name](#usage-and-name)
|
||||
- [.helpOption(flags, description)](#helpoptionflags-description)
|
||||
- [.addHelpCommand()](#addhelpcommand)
|
||||
- [More configuration](#more-configuration-1)
|
||||
- [Custom event listeners](#custom-event-listeners)
|
||||
- [Bits and pieces](#bits-and-pieces)
|
||||
- [.parse() and .parseAsync()](#parse-and-parseasync)
|
||||
- [Parsing Configuration](#parsing-configuration)
|
||||
- [Legacy options as properties](#legacy-options-as-properties)
|
||||
- [TypeScript](#typescript)
|
||||
- [createCommand()](#createcommand)
|
||||
- [Node options such as `--harmony`](#node-options-such-as---harmony)
|
||||
- [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
|
||||
- [Override exit and output handling](#override-exit-and-output-handling)
|
||||
- [Additional documentation](#additional-documentation)
|
||||
- [Examples](#examples)
|
||||
- [Support](#support)
|
||||
- [Commander for enterprise](#commander-for-enterprise)
|
||||
|
||||
For information about terms used in this document see: [terminology](./docs/terminology.md)
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install commander
|
||||
```
|
||||
|
||||
## Declaring _program_ variable
|
||||
|
||||
Commander exports a global object which is convenient for quick programs.
|
||||
This is used in the examples in this README for brevity.
|
||||
|
||||
```js
|
||||
const { program } = require('commander');
|
||||
program.version('0.0.1');
|
||||
```
|
||||
|
||||
For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
|
||||
|
||||
```js
|
||||
const { Command } = require('commander');
|
||||
const program = new Command();
|
||||
program.version('0.0.1');
|
||||
```
|
||||
|
||||
For named imports in ECMAScript modules, import from `commander/esm.mjs`.
|
||||
|
||||
```js
|
||||
// index.mjs
|
||||
import { Command } from 'commander/esm.mjs';
|
||||
const program = new Command();
|
||||
```
|
||||
|
||||
And in TypeScript:
|
||||
|
||||
```ts
|
||||
// index.ts
|
||||
import { Command } from 'commander';
|
||||
const program = new Command();
|
||||
```
|
||||
|
||||
|
||||
## Options
|
||||
|
||||
Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').
|
||||
|
||||
The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
|
||||
|
||||
Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
|
||||
For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
|
||||
|
||||
You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
|
||||
|
||||
By default options on the command line are not positional, and can be specified before or after other arguments.
|
||||
|
||||
### Common option types, boolean and value
|
||||
|
||||
The two most used option types are a boolean option, and an option which takes its value
|
||||
from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
|
||||
|
||||
Example file: [options-common.js](./examples/options-common.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('-d, --debug', 'output extra debugging')
|
||||
.option('-s, --small', 'small pizza size')
|
||||
.option('-p, --pizza-type <type>', 'flavour of pizza');
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
const options = program.opts();
|
||||
if (options.debug) console.log(options);
|
||||
console.log('pizza details:');
|
||||
if (options.small) console.log('- small pizza size');
|
||||
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ pizza-options -d
|
||||
{ debug: true, small: undefined, pizzaType: undefined }
|
||||
pizza details:
|
||||
$ pizza-options -p
|
||||
error: option '-p, --pizza-type <type>' argument missing
|
||||
$ pizza-options -ds -p vegetarian
|
||||
{ debug: true, small: true, pizzaType: 'vegetarian' }
|
||||
pizza details:
|
||||
- small pizza size
|
||||
- vegetarian
|
||||
$ pizza-options --pizza-type=cheese
|
||||
pizza details:
|
||||
- cheese
|
||||
```
|
||||
|
||||
`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.
|
||||
|
||||
### Default option value
|
||||
|
||||
You can specify a default value for an option which takes a value.
|
||||
|
||||
Example file: [options-defaults.js](./examples/options-defaults.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
|
||||
|
||||
program.parse();
|
||||
|
||||
console.log(`cheese: ${program.opts().cheese}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ pizza-options
|
||||
cheese: blue
|
||||
$ pizza-options --cheese stilton
|
||||
cheese: stilton
|
||||
```
|
||||
|
||||
### Other option types, negatable boolean and boolean|value
|
||||
|
||||
You can define a boolean option long name with a leading `no-` to set the option value to false when used.
|
||||
Defined alone this also makes the option true by default.
|
||||
|
||||
If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
|
||||
otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line.
|
||||
|
||||
Example file: [options-negatable.js](./examples/options-negatable.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('--no-sauce', 'Remove sauce')
|
||||
.option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
|
||||
.option('--no-cheese', 'plain with no cheese')
|
||||
.parse();
|
||||
|
||||
const options = program.opts();
|
||||
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
|
||||
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
|
||||
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ pizza-options
|
||||
You ordered a pizza with sauce and mozzarella cheese
|
||||
$ pizza-options --sauce
|
||||
error: unknown option '--sauce'
|
||||
$ pizza-options --cheese=blue
|
||||
You ordered a pizza with sauce and blue cheese
|
||||
$ pizza-options --no-sauce --no-cheese
|
||||
You ordered a pizza with no sauce and no cheese
|
||||
```
|
||||
|
||||
You can specify an option which may be used as a boolean option but may optionally take an option-argument
|
||||
(declared with square brackets like `--optional [value]`).
|
||||
|
||||
Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('-c, --cheese [type]', 'Add cheese with optional type');
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
const options = program.opts();
|
||||
if (options.cheese === undefined) console.log('no cheese');
|
||||
else if (options.cheese === true) console.log('add cheese');
|
||||
else console.log(`add cheese type ${options.cheese}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ pizza-options
|
||||
no cheese
|
||||
$ pizza-options --cheese
|
||||
add cheese
|
||||
$ pizza-options --cheese mozzarella
|
||||
add cheese type mozzarella
|
||||
```
|
||||
|
||||
For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
|
||||
|
||||
### Required option
|
||||
|
||||
You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.
|
||||
|
||||
Example file: [options-required.js](./examples/options-required.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.requiredOption('-c, --cheese <type>', 'pizza must have cheese');
|
||||
|
||||
program.parse();
|
||||
```
|
||||
|
||||
```bash
|
||||
$ pizza
|
||||
error: required option '-c, --cheese <type>' not specified
|
||||
```
|
||||
|
||||
### Variadic option
|
||||
|
||||
You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
|
||||
can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
|
||||
are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
|
||||
is specified in the same argument as the option then no further values are read.
|
||||
|
||||
Example file: [options-variadic.js](./examples/options-variadic.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('-n, --number <numbers...>', 'specify numbers')
|
||||
.option('-l, --letter [letters...]', 'specify letters');
|
||||
|
||||
program.parse();
|
||||
|
||||
console.log('Options: ', program.opts());
|
||||
console.log('Remaining arguments: ', program.args);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ collect -n 1 2 3 --letter a b c
|
||||
Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
|
||||
Remaining arguments: []
|
||||
$ collect --letter=A -n80 operand
|
||||
Options: { number: [ '80' ], letter: [ 'A' ] }
|
||||
Remaining arguments: [ 'operand' ]
|
||||
$ collect --letter -n 1 -n 2 3 -- operand
|
||||
Options: { number: [ '1', '2', '3' ], letter: true }
|
||||
Remaining arguments: [ 'operand' ]
|
||||
```
|
||||
|
||||
For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
|
||||
|
||||
### Version option
|
||||
|
||||
The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
|
||||
|
||||
```js
|
||||
program.version('0.0.1');
|
||||
```
|
||||
|
||||
```bash
|
||||
$ ./examples/pizza -V
|
||||
0.0.1
|
||||
```
|
||||
|
||||
You may change the flags and description by passing additional parameters to the `version` method, using
|
||||
the same syntax for flags as the `option` method.
|
||||
|
||||
```js
|
||||
program.version('0.0.1', '-v, --vers', 'output the current version');
|
||||
```
|
||||
|
||||
### More configuration
|
||||
|
||||
You can add most options using the `.option()` method, but there are some additional features available
|
||||
by constructing an `Option` explicitly for less common cases.
|
||||
|
||||
Example file: [options-extra.js](./examples/options-extra.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.addOption(new Option('-s, --secret').hideHelp())
|
||||
.addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
|
||||
.addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']));
|
||||
```
|
||||
|
||||
```bash
|
||||
$ extra --help
|
||||
Usage: help [options]
|
||||
|
||||
Options:
|
||||
-t, --timeout <delay> timeout in seconds (default: one minute)
|
||||
-d, --drink <size> drink cup size (choices: "small", "medium", "large")
|
||||
-h, --help display help for command
|
||||
|
||||
$ extra --drink huge
|
||||
error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
|
||||
```
|
||||
|
||||
### Custom option processing
|
||||
|
||||
You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
|
||||
the user specified option-argument and the previous value for the option. It returns the new value for the option.
|
||||
|
||||
This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
|
||||
|
||||
You can optionally specify the default/starting value for the option after the function parameter.
|
||||
|
||||
Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
|
||||
|
||||
```js
|
||||
function myParseInt(value, dummyPrevious) {
|
||||
// parseInt takes a string and a radix
|
||||
const parsedValue = parseInt(value, 10);
|
||||
if (isNaN(parsedValue)) {
|
||||
throw new commander.InvalidOptionArgumentError('Not a number.');
|
||||
}
|
||||
return parsedValue;
|
||||
}
|
||||
|
||||
function increaseVerbosity(dummyValue, previous) {
|
||||
return previous + 1;
|
||||
}
|
||||
|
||||
function collect(value, previous) {
|
||||
return previous.concat([value]);
|
||||
}
|
||||
|
||||
function commaSeparatedList(value, dummyPrevious) {
|
||||
return value.split(',');
|
||||
}
|
||||
|
||||
program
|
||||
.option('-f, --float <number>', 'float argument', parseFloat)
|
||||
.option('-i, --integer <number>', 'integer argument', myParseInt)
|
||||
.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
|
||||
.option('-c, --collect <value>', 'repeatable value', collect, [])
|
||||
.option('-l, --list <items>', 'comma separated list', commaSeparatedList)
|
||||
;
|
||||
|
||||
program.parse();
|
||||
|
||||
const options = program.opts();
|
||||
if (options.float !== undefined) console.log(`float: ${options.float}`);
|
||||
if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
|
||||
if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
|
||||
if (options.collect.length > 0) console.log(options.collect);
|
||||
if (options.list !== undefined) console.log(options.list);
|
||||
```
|
||||
|
||||
```bash
|
||||
$ custom -f 1e2
|
||||
float: 100
|
||||
$ custom --integer 2
|
||||
integer: 2
|
||||
$ custom -v -v -v
|
||||
verbose: 3
|
||||
$ custom -c a -c b -c c
|
||||
[ 'a', 'b', 'c' ]
|
||||
$ custom --list x,y,z
|
||||
[ 'x', 'y', 'z' ]
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
|
||||
|
||||
In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
|
||||
|
||||
You can use `.addCommand()` to add an already configured subcommand to the program.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
// Command implemented using action handler (description is supplied separately to `.command`)
|
||||
// Returns new command for configuring.
|
||||
program
|
||||
.command('clone <source> [destination]')
|
||||
.description('clone a repository into a newly created directory')
|
||||
.action((source, destination) => {
|
||||
console.log('clone command called');
|
||||
});
|
||||
|
||||
// Command implemented using stand-alone executable file (description is second parameter to `.command`)
|
||||
// Returns `this` for adding more commands.
|
||||
program
|
||||
.command('start <service>', 'start named service')
|
||||
.command('stop [service]', 'stop named service, or all if no name supplied');
|
||||
|
||||
// Command prepared separately.
|
||||
// Returns `this` for adding more commands.
|
||||
program
|
||||
.addCommand(build.makeBuildCommand());
|
||||
```
|
||||
|
||||
Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
|
||||
remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
|
||||
subcommand is specified ([example](./examples/defaultCommand.js)).
|
||||
|
||||
### Specify the argument syntax
|
||||
|
||||
You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually
|
||||
included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.
|
||||
Square brackets (e.g. `[optional]`) indicate optional command-arguments.
|
||||
You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.
|
||||
|
||||
Example file: [arguments.js](./examples/arguments.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.version('0.1.0')
|
||||
.arguments('<username> [password]')
|
||||
.description('test command', {
|
||||
username: 'user to login',
|
||||
password: 'password for user, if required'
|
||||
})
|
||||
.action((username, password) => {
|
||||
console.log('username:', username);
|
||||
console.log('environment:', password || 'no password given');
|
||||
});
|
||||
```
|
||||
|
||||
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
|
||||
append `...` to the argument name. For example:
|
||||
|
||||
```js
|
||||
program
|
||||
.version('0.1.0')
|
||||
.command('rmdir <dirs...>')
|
||||
.action(function (dirs) {
|
||||
dirs.forEach((dir) => {
|
||||
console.log('rmdir %s', dir);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The variadic argument is passed to the action handler as an array.
|
||||
|
||||
### Action handler
|
||||
|
||||
The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
|
||||
which are the parsed options and the command object itself.
|
||||
|
||||
Example file: [thank.js](./examples/thank.js)
|
||||
|
||||
```js
|
||||
program
|
||||
.arguments('<name>')
|
||||
.option('-t, --title <honorific>', 'title to use before name')
|
||||
.option('-d, --debug', 'display some debugging')
|
||||
.action((name, options, command) => {
|
||||
if (options.debug) {
|
||||
console.error('Called %s with options %o', command.name(), options);
|
||||
}
|
||||
const title = options.title ? `${options.title} ` : '';
|
||||
console.log(`Thank-you ${title}${name}`);
|
||||
});
|
||||
```
|
||||
|
||||
You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
|
||||
|
||||
```js
|
||||
async function run() { /* code goes here */ }
|
||||
|
||||
async function main() {
|
||||
program
|
||||
.command('run')
|
||||
.action(run);
|
||||
await program.parseAsync(process.argv);
|
||||
}
|
||||
```
|
||||
|
||||
A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to
|
||||
pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.
|
||||
|
||||
### Stand-alone executable (sub)commands
|
||||
|
||||
When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
|
||||
Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
|
||||
You can specify a custom name with the `executableFile` configuration option.
|
||||
|
||||
You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
|
||||
|
||||
Example file: [pm](./examples/pm)
|
||||
|
||||
```js
|
||||
program
|
||||
.version('0.1.0')
|
||||
.command('install [name]', 'install one or more packages')
|
||||
.command('search [query]', 'search with optional query')
|
||||
.command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
|
||||
.command('list', 'list packages installed', { isDefault: true });
|
||||
|
||||
program.parse(process.argv);
|
||||
```
|
||||
|
||||
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
|
||||
|
||||
## Automated help
|
||||
|
||||
The help information is auto-generated based on the information commander already knows about your program. The default
|
||||
help option is `-h,--help`.
|
||||
|
||||
Example file: [pizza](./examples/pizza)
|
||||
|
||||
```bash
|
||||
$ node ./examples/pizza --help
|
||||
Usage: pizza [options]
|
||||
|
||||
An application for pizza ordering
|
||||
|
||||
Options:
|
||||
-p, --peppers Add peppers
|
||||
-c, --cheese <type> Add the specified type of cheese (default: "marble")
|
||||
-C, --no-cheese You do not want any cheese
|
||||
-h, --help display help for command
|
||||
```
|
||||
|
||||
A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
|
||||
further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
|
||||
|
||||
```bash
|
||||
shell help
|
||||
shell --help
|
||||
|
||||
shell help spawn
|
||||
shell spawn --help
|
||||
```
|
||||
|
||||
### Custom help
|
||||
|
||||
You can add extra text to be displayed along with the built-in help.
|
||||
|
||||
Example file: [custom-help](./examples/custom-help)
|
||||
|
||||
```js
|
||||
program
|
||||
.option('-f, --foo', 'enable some foo');
|
||||
|
||||
program.addHelpText('after', `
|
||||
|
||||
Example call:
|
||||
$ custom-help --help`);
|
||||
```
|
||||
|
||||
Yields the following help output:
|
||||
|
||||
```Text
|
||||
Usage: custom-help [options]
|
||||
|
||||
Options:
|
||||
-f, --foo enable some foo
|
||||
-h, --help display help for command
|
||||
|
||||
Example call:
|
||||
$ custom-help --help
|
||||
```
|
||||
|
||||
The positions in order displayed are:
|
||||
|
||||
- `beforeAll`: add to the program for a global banner or header
|
||||
- `before`: display extra information before built-in help
|
||||
- `after`: display extra information after built-in help
|
||||
- `afterAll`: add to the program for a global footer (epilog)
|
||||
|
||||
The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
|
||||
|
||||
The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:
|
||||
|
||||
- error: a boolean for whether the help is being displayed due to a usage error
|
||||
- command: the Command which is displaying the help
|
||||
|
||||
### Display help from code
|
||||
|
||||
`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
|
||||
|
||||
`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
|
||||
|
||||
`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
|
||||
|
||||
### .usage and .name
|
||||
|
||||
These allow you to customise the usage description in the first line of the help. The name is otherwise
|
||||
deduced from the (full) program arguments. Given:
|
||||
|
||||
```js
|
||||
program
|
||||
.name("my-command")
|
||||
.usage("[global options] command")
|
||||
```
|
||||
|
||||
The help will start with:
|
||||
|
||||
```Text
|
||||
Usage: my-command [global options] command
|
||||
```
|
||||
|
||||
### .helpOption(flags, description)
|
||||
|
||||
By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.
|
||||
|
||||
```js
|
||||
program
|
||||
.helpOption('-e, --HELP', 'read more information');
|
||||
```
|
||||
|
||||
### .addHelpCommand()
|
||||
|
||||
A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
|
||||
|
||||
You can both turn on and customise the help command by supplying the name and description:
|
||||
|
||||
```js
|
||||
program.addHelpCommand('assist [command]', 'show assistance');
|
||||
```
|
||||
|
||||
### More configuration
|
||||
|
||||
The built-in help is formatted using the Help class.
|
||||
You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.
|
||||
|
||||
The data properties are:
|
||||
|
||||
- `helpWidth`: specify the wrap width, useful for unit tests
|
||||
- `sortSubcommands`: sort the subcommands alphabetically
|
||||
- `sortOptions`: sort the options alphabetically
|
||||
|
||||
There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.
|
||||
|
||||
Example file: [configure-help.js](./examples/configure-help.js)
|
||||
|
||||
```
|
||||
program.configureHelp({
|
||||
sortSubcommands: true,
|
||||
subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
|
||||
});
|
||||
```
|
||||
|
||||
## Custom event listeners
|
||||
|
||||
You can execute custom actions by listening to command and option events.
|
||||
|
||||
```js
|
||||
program.on('option:verbose', function () {
|
||||
process.env.VERBOSE = this.opts().verbose;
|
||||
});
|
||||
|
||||
program.on('command:*', function (operands) {
|
||||
console.error(`error: unknown command '${operands[0]}'`);
|
||||
const availableCommands = program.commands.map(cmd => cmd.name());
|
||||
mySuggestBestMatch(operands[0], availableCommands);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
```
|
||||
|
||||
## Bits and pieces
|
||||
|
||||
### .parse() and .parseAsync()
|
||||
|
||||
The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
|
||||
|
||||
If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
|
||||
|
||||
- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
|
||||
- 'electron': `argv[1]` varies depending on whether the electron application is packaged
|
||||
- 'user': all of the arguments from the user
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
program.parse(process.argv); // Explicit, node conventions
|
||||
program.parse(); // Implicit, and auto-detect electron
|
||||
program.parse(['-f', 'filename'], { from: 'user' });
|
||||
```
|
||||
|
||||
### Parsing Configuration
|
||||
|
||||
If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
|
||||
|
||||
By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
|
||||
an option for a different purpose in subcommands.
|
||||
|
||||
Example file: [positional-options.js](./examples/positional-options.js)
|
||||
|
||||
With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
|
||||
|
||||
```sh
|
||||
program -b subcommand
|
||||
program subcommand -b
|
||||
```
|
||||
|
||||
By default options are recognised before and after command-arguments. To only process options that come
|
||||
before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
|
||||
without needing to use `--` to end the option processing.
|
||||
To use pass through options in a subcommand, the program needs to enable positional options.
|
||||
|
||||
Example file: [pass-through-options.js](./examples/pass-through-options.js)
|
||||
|
||||
With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:
|
||||
|
||||
```sh
|
||||
program --port=80 arg
|
||||
program arg --port=80
|
||||
```
|
||||
|
||||
By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.
|
||||
|
||||
By default the argument processing does not display an error for more command-arguments than expected.
|
||||
To display an error for excess arguments, use`.allowExcessArguments(false)`.
|
||||
|
||||
### Legacy options as properties
|
||||
|
||||
Before Commander 7, the option values were stored as properties on the command.
|
||||
This was convenient to code but the downside was possible clashes with
|
||||
existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
|
||||
|
||||
```js
|
||||
program
|
||||
.storeOptionsAsProperties()
|
||||
.option('-d, --debug')
|
||||
.action((commandAndOptions) => {
|
||||
if (commandAndOptions.debug) {
|
||||
console.error(`Called ${commandAndOptions.name()}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.
|
||||
|
||||
```bash
|
||||
node -r ts-node/register pm.ts
|
||||
```
|
||||
|
||||
### createCommand()
|
||||
|
||||
This factory function creates a new command. It is exported and may be used instead of using `new`, like:
|
||||
|
||||
```js
|
||||
const { createCommand } = require('commander');
|
||||
const program = createCommand();
|
||||
```
|
||||
|
||||
`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
|
||||
when creating subcommands using `.command()`, and you may override it to
|
||||
customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
|
||||
|
||||
### Node options such as `--harmony`
|
||||
|
||||
You can enable `--harmony` option in two ways:
|
||||
|
||||
- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
|
||||
- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
|
||||
|
||||
### Debugging stand-alone executable subcommands
|
||||
|
||||
An executable subcommand is launched as a separate child process.
|
||||
|
||||
If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
|
||||
the inspector port is incremented by 1 for the spawned subcommand.
|
||||
|
||||
If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
|
||||
|
||||
### Override exit and output handling
|
||||
|
||||
By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
|
||||
this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
|
||||
|
||||
The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
|
||||
is not affected by the override which is called after the display.
|
||||
|
||||
```js
|
||||
program.exitOverride();
|
||||
|
||||
try {
|
||||
program.parse(process.argv);
|
||||
} catch (err) {
|
||||
// custom processing...
|
||||
}
|
||||
```
|
||||
|
||||
By default Commander is configured for a command-line application and writes to stdout and stderr.
|
||||
You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
|
||||
|
||||
Example file: [configure-output.js](./examples/configure-output.js)
|
||||
|
||||
|
||||
```js
|
||||
function errorColor(str) {
|
||||
// Add ANSI escape codes to display text in red.
|
||||
return `\x1b[31m${str}\x1b[0m`;
|
||||
}
|
||||
|
||||
program
|
||||
.configureOutput({
|
||||
// Visibly override write routines as example!
|
||||
writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
|
||||
writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
|
||||
// Highlight errors in color.
|
||||
outputError: (str, write) => write(errorColor(str))
|
||||
});
|
||||
```
|
||||
|
||||
### Additional documentation
|
||||
|
||||
There is more information available about:
|
||||
|
||||
- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
|
||||
- [options taking varying arguments](./docs/options-taking-varying-arguments.md)
|
||||
|
||||
## Examples
|
||||
|
||||
In a single command program, you might not need an action handler.
|
||||
|
||||
Example file: [pizza](./examples/pizza)
|
||||
|
||||
```js
|
||||
const { program } = require('commander');
|
||||
|
||||
program
|
||||
.description('An application for pizza ordering')
|
||||
.option('-p, --peppers', 'Add peppers')
|
||||
.option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')
|
||||
.option('-C, --no-cheese', 'You do not want any cheese');
|
||||
|
||||
program.parse();
|
||||
|
||||
const options = program.opts();
|
||||
console.log('you ordered a pizza with:');
|
||||
if (options.peppers) console.log(' - peppers');
|
||||
const cheese = !options.cheese ? 'no' : options.cheese;
|
||||
console.log(' - %s cheese', cheese);
|
||||
```
|
||||
|
||||
In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).
|
||||
|
||||
Example file: [deploy](./examples/deploy)
|
||||
|
||||
```js
|
||||
const { Command } = require('commander');
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.version('0.0.1')
|
||||
.option('-c, --config <path>', 'set config path', './deploy.conf');
|
||||
|
||||
program
|
||||
.command('setup [env]')
|
||||
.description('run setup commands for all envs')
|
||||
.option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')
|
||||
.action((env, options) => {
|
||||
env = env || 'all';
|
||||
console.log('read config from %s', program.opts().config);
|
||||
console.log('setup for %s env(s) with %s mode', env, options.setup_mode);
|
||||
});
|
||||
|
||||
program
|
||||
.command('exec <script>')
|
||||
.alias('ex')
|
||||
.description('execute the given remote cmd')
|
||||
.option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')
|
||||
.action((script, options) => {
|
||||
console.log('read config from %s', program.opts().config);
|
||||
console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);
|
||||
}).addHelpText('after', `
|
||||
Examples:
|
||||
$ deploy exec sequential
|
||||
$ deploy exec async`
|
||||
);
|
||||
|
||||
program.parse(process.argv);
|
||||
```
|
||||
|
||||
More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
|
||||
|
||||
## Support
|
||||
|
||||
The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v10.
|
||||
(For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.)
|
||||
|
||||
The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
|
||||
|
||||
### Commander for enterprise
|
||||
|
||||
Available as part of the Tidelift Subscription
|
||||
|
||||
The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
4
node_modules/svgo/node_modules/commander/esm.mjs
generated
vendored
Normal file
4
node_modules/svgo/node_modules/commander/esm.mjs
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import commander from './index.js';
|
||||
|
||||
// wrapper to provide named exports for ESM.
|
||||
export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander;
|
||||
2217
node_modules/svgo/node_modules/commander/index.js
generated
vendored
Normal file
2217
node_modules/svgo/node_modules/commander/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
16
node_modules/svgo/node_modules/commander/package-support.json
generated
vendored
Normal file
16
node_modules/svgo/node_modules/commander/package-support.json
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"version": "*",
|
||||
"target": {
|
||||
"node": "supported"
|
||||
},
|
||||
"response": {
|
||||
"type": "time-permitting"
|
||||
},
|
||||
"backing": {
|
||||
"npm-funding": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
68
node_modules/svgo/node_modules/commander/package.json
generated
vendored
Normal file
68
node_modules/svgo/node_modules/commander/package.json
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "commander",
|
||||
"version": "7.2.0",
|
||||
"description": "the complete solution for node.js command-line programs",
|
||||
"keywords": [
|
||||
"commander",
|
||||
"command",
|
||||
"option",
|
||||
"parser",
|
||||
"cli",
|
||||
"argument",
|
||||
"args",
|
||||
"argv"
|
||||
],
|
||||
"author": "TJ Holowaychuk <tj@vision-media.ca>",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/tj/commander.js.git"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint index.js esm.mjs \"tests/**/*.js\"",
|
||||
"typescript-lint": "eslint typings/*.ts tests/*.ts",
|
||||
"test": "jest && npm run test-typings",
|
||||
"test-esm": "node --experimental-modules ./tests/esm-imports-test.mjs",
|
||||
"test-typings": "tsd",
|
||||
"typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit",
|
||||
"test-all": "npm run test && npm run lint && npm run typescript-lint && npm run typescript-checkJS && npm run test-esm"
|
||||
},
|
||||
"main": "./index.js",
|
||||
"files": [
|
||||
"index.js",
|
||||
"esm.mjs",
|
||||
"typings/index.d.ts",
|
||||
"package-support.json"
|
||||
],
|
||||
"type": "commonjs",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^26.0.20",
|
||||
"@types/node": "^14.14.20",
|
||||
"@typescript-eslint/eslint-plugin": "^4.12.0",
|
||||
"@typescript-eslint/parser": "^4.12.0",
|
||||
"eslint": "^7.17.0",
|
||||
"eslint-config-standard": "^16.0.2",
|
||||
"eslint-plugin-jest": "^24.1.3",
|
||||
"jest": "^26.6.3",
|
||||
"standard": "^16.0.3",
|
||||
"ts-jest": "^26.5.1",
|
||||
"tsd": "^0.14.0",
|
||||
"typescript": "^4.1.2"
|
||||
},
|
||||
"types": "typings/index.d.ts",
|
||||
"jest": {
|
||||
"testEnvironment": "node",
|
||||
"collectCoverage": true,
|
||||
"transform": {
|
||||
"^.+\\.tsx?$": "ts-jest"
|
||||
},
|
||||
"testPathIgnorePatterns": [
|
||||
"/node_modules/"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"support": true
|
||||
}
|
||||
627
node_modules/svgo/node_modules/commander/typings/index.d.ts
generated
vendored
Normal file
627
node_modules/svgo/node_modules/commander/typings/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,627 @@
|
||||
// Type definitions for commander
|
||||
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
|
||||
|
||||
// Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
|
||||
/* eslint-disable @typescript-eslint/method-signature-style */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
declare namespace commander {
|
||||
|
||||
interface CommanderError extends Error {
|
||||
code: string;
|
||||
exitCode: number;
|
||||
message: string;
|
||||
nestedError?: string;
|
||||
}
|
||||
type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
interface InvalidOptionArgumentError extends CommanderError {
|
||||
}
|
||||
type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;
|
||||
|
||||
interface Option {
|
||||
flags: string;
|
||||
description: string;
|
||||
|
||||
required: boolean; // A value must be supplied when the option is specified.
|
||||
optional: boolean; // A value is optional when the option is specified.
|
||||
variadic: boolean;
|
||||
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
|
||||
optionFlags: string;
|
||||
short?: string;
|
||||
long?: string;
|
||||
negate: boolean;
|
||||
defaultValue?: any;
|
||||
defaultValueDescription?: string;
|
||||
parseArg?: <T>(value: string, previous: T) => T;
|
||||
hidden: boolean;
|
||||
argChoices?: string[];
|
||||
|
||||
/**
|
||||
* Set the default value, and optionally supply the description to be displayed in the help.
|
||||
*/
|
||||
default(value: any, description?: string): this;
|
||||
|
||||
/**
|
||||
* Calculate the full description, including defaultValue etc.
|
||||
*/
|
||||
fullDescription(): string;
|
||||
|
||||
/**
|
||||
* Set the custom handler for processing CLI option arguments into option values.
|
||||
*/
|
||||
argParser<T>(fn: (value: string, previous: T) => T): this;
|
||||
|
||||
/**
|
||||
* Whether the option is mandatory and must have a value after parsing.
|
||||
*/
|
||||
makeOptionMandatory(mandatory?: boolean): this;
|
||||
|
||||
/**
|
||||
* Hide option in help.
|
||||
*/
|
||||
hideHelp(hide?: boolean): this;
|
||||
|
||||
/**
|
||||
* Validation of option argument failed.
|
||||
* Intended for use from custom argument processing functions.
|
||||
*/
|
||||
argumentRejected(messsage: string): never;
|
||||
|
||||
/**
|
||||
* Only allow option value to be one of choices.
|
||||
*/
|
||||
choices(values: string[]): this;
|
||||
|
||||
/**
|
||||
* Return option name.
|
||||
*/
|
||||
name(): string;
|
||||
|
||||
/**
|
||||
* Return option name, in a camelcase format that can be used
|
||||
* as a object attribute key.
|
||||
*/
|
||||
attributeName(): string;
|
||||
}
|
||||
type OptionConstructor = new (flags: string, description?: string) => Option;
|
||||
|
||||
interface Help {
|
||||
/** output helpWidth, long lines are wrapped to fit */
|
||||
helpWidth?: number;
|
||||
sortSubcommands: boolean;
|
||||
sortOptions: boolean;
|
||||
|
||||
/** Get the command term to show in the list of subcommands. */
|
||||
subcommandTerm(cmd: Command): string;
|
||||
/** Get the command description to show in the list of subcommands. */
|
||||
subcommandDescription(cmd: Command): string;
|
||||
/** Get the option term to show in the list of options. */
|
||||
optionTerm(option: Option): string;
|
||||
/** Get the option description to show in the list of options. */
|
||||
optionDescription(option: Option): string;
|
||||
|
||||
/** Get the command usage to be displayed at the top of the built-in help. */
|
||||
commandUsage(cmd: Command): string;
|
||||
/** Get the description for the command. */
|
||||
commandDescription(cmd: Command): string;
|
||||
|
||||
/** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
|
||||
visibleCommands(cmd: Command): Command[];
|
||||
/** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
|
||||
visibleOptions(cmd: Command): Option[];
|
||||
/** Get an array of the arguments which have descriptions. */
|
||||
visibleArguments(cmd: Command): Array<{ term: string; description: string}>;
|
||||
|
||||
/** Get the longest command term length. */
|
||||
longestSubcommandTermLength(cmd: Command, helper: Help): number;
|
||||
/** Get the longest option term length. */
|
||||
longestOptionTermLength(cmd: Command, helper: Help): number;
|
||||
/** Get the longest argument term length. */
|
||||
longestArgumentTermLength(cmd: Command, helper: Help): number;
|
||||
/** Calculate the pad width from the maximum term length. */
|
||||
padWidth(cmd: Command, helper: Help): number;
|
||||
|
||||
/**
|
||||
* Wrap the given string to width characters per line, with lines after the first indented.
|
||||
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
|
||||
*/
|
||||
wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
|
||||
|
||||
/** Generate the built-in help text. */
|
||||
formatHelp(cmd: Command, helper: Help): string;
|
||||
}
|
||||
type HelpConstructor = new () => Help;
|
||||
type HelpConfiguration = Partial<Help>;
|
||||
|
||||
interface ParseOptions {
|
||||
from: 'node' | 'electron' | 'user';
|
||||
}
|
||||
interface HelpContext { // optional parameter for .help() and .outputHelp()
|
||||
error: boolean;
|
||||
}
|
||||
interface AddHelpTextContext { // passed to text function used with .addHelpText()
|
||||
error: boolean;
|
||||
command: Command;
|
||||
}
|
||||
interface OutputConfiguration {
|
||||
writeOut?(str: string): void;
|
||||
writeErr?(str: string): void;
|
||||
getOutHelpWidth?(): number;
|
||||
getErrHelpWidth?(): number;
|
||||
outputError?(str: string, write: (str: string) => void): void;
|
||||
|
||||
}
|
||||
|
||||
type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
|
||||
|
||||
interface OptionValues {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
interface Command {
|
||||
args: string[];
|
||||
commands: Command[];
|
||||
parent: Command | null;
|
||||
|
||||
/**
|
||||
* Set the program version to `str`.
|
||||
*
|
||||
* This method auto-registers the "-V, --version" flag
|
||||
* which will print the version number when passed.
|
||||
*
|
||||
* You can optionally supply the flags and description to override the defaults.
|
||||
*/
|
||||
version(str: string, flags?: string, description?: string): this;
|
||||
|
||||
/**
|
||||
* Define a command, implemented using an action handler.
|
||||
*
|
||||
* @remarks
|
||||
* The command description is supplied using `.description`, not as a parameter to `.command`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* program
|
||||
* .command('clone <source> [destination]')
|
||||
* .description('clone a repository into a newly created directory')
|
||||
* .action((source, destination) => {
|
||||
* console.log('clone command called');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
||||
* @param opts - configuration options
|
||||
* @returns new command
|
||||
*/
|
||||
command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
|
||||
/**
|
||||
* Define a command, implemented in a separate executable file.
|
||||
*
|
||||
* @remarks
|
||||
* The command description is supplied as the second parameter to `.command`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* program
|
||||
* .command('start <service>', 'start named service')
|
||||
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
||||
* ```
|
||||
*
|
||||
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
||||
* @param description - description of executable command
|
||||
* @param opts - configuration options
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this;
|
||||
|
||||
/**
|
||||
* Factory routine to create a new unattached command.
|
||||
*
|
||||
* See .command() for creating an attached subcommand, which uses this routine to
|
||||
* create the command. You can override createCommand to customise subcommands.
|
||||
*/
|
||||
createCommand(name?: string): Command;
|
||||
|
||||
/**
|
||||
* Add a prepared subcommand.
|
||||
*
|
||||
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
addCommand(cmd: Command, opts?: CommandOptions): this;
|
||||
|
||||
/**
|
||||
* Define argument syntax for command.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
arguments(desc: string): this;
|
||||
|
||||
/**
|
||||
* Override default decision whether to add implicit help command.
|
||||
*
|
||||
* addHelpCommand() // force on
|
||||
* addHelpCommand(false); // force off
|
||||
* addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
|
||||
|
||||
/**
|
||||
* Register callback to use as replacement for calling process.exit.
|
||||
*/
|
||||
exitOverride(callback?: (err: CommanderError) => never|void): this;
|
||||
|
||||
/**
|
||||
* You can customise the help with a subclass of Help by overriding createHelp,
|
||||
* or by overriding Help properties using configureHelp().
|
||||
*/
|
||||
createHelp(): Help;
|
||||
|
||||
/**
|
||||
* You can customise the help by overriding Help properties using configureHelp(),
|
||||
* or with a subclass of Help by overriding createHelp().
|
||||
*/
|
||||
configureHelp(configuration: HelpConfiguration): this;
|
||||
/** Get configuration */
|
||||
configureHelp(): HelpConfiguration;
|
||||
|
||||
/**
|
||||
* The default output goes to stdout and stderr. You can customise this for special
|
||||
* applications. You can also customise the display of errors by overriding outputError.
|
||||
*
|
||||
* The configuration properties are all functions:
|
||||
*
|
||||
* // functions to change where being written, stdout and stderr
|
||||
* writeOut(str)
|
||||
* writeErr(str)
|
||||
* // matching functions to specify width for wrapping help
|
||||
* getOutHelpWidth()
|
||||
* getErrHelpWidth()
|
||||
* // functions based on what is being written out
|
||||
* outputError(str, write) // used for displaying errors, and not used for displaying help
|
||||
*/
|
||||
configureOutput(configuration: OutputConfiguration): this;
|
||||
/** Get configuration */
|
||||
configureOutput(): OutputConfiguration;
|
||||
|
||||
/**
|
||||
* Register callback `fn` for the command.
|
||||
*
|
||||
* @example
|
||||
* program
|
||||
* .command('help')
|
||||
* .description('display verbose help')
|
||||
* .action(function() {
|
||||
* // output help here
|
||||
* });
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
action(fn: (...args: any[]) => void | Promise<void>): this;
|
||||
|
||||
/**
|
||||
* Define option with `flags`, `description` and optional
|
||||
* coercion `fn`.
|
||||
*
|
||||
* The `flags` string contains the short and/or long flags,
|
||||
* separated by comma, a pipe or space. The following are all valid
|
||||
* all will output this way when `--help` is used.
|
||||
*
|
||||
* "-p, --pepper"
|
||||
* "-p|--pepper"
|
||||
* "-p --pepper"
|
||||
*
|
||||
* @example
|
||||
* // simple boolean defaulting to false
|
||||
* program.option('-p, --pepper', 'add pepper');
|
||||
*
|
||||
* --pepper
|
||||
* program.pepper
|
||||
* // => Boolean
|
||||
*
|
||||
* // simple boolean defaulting to true
|
||||
* program.option('-C, --no-cheese', 'remove cheese');
|
||||
*
|
||||
* program.cheese
|
||||
* // => true
|
||||
*
|
||||
* --no-cheese
|
||||
* program.cheese
|
||||
* // => false
|
||||
*
|
||||
* // required argument
|
||||
* program.option('-C, --chdir <path>', 'change the working directory');
|
||||
*
|
||||
* --chdir /tmp
|
||||
* program.chdir
|
||||
* // => "/tmp"
|
||||
*
|
||||
* // optional argument
|
||||
* program.option('-c, --cheese [type]', 'add cheese [marble]');
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
option(flags: string, description?: string, defaultValue?: string | boolean): this;
|
||||
option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
|
||||
/** @deprecated since v7, instead use choices or a custom function */
|
||||
option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
|
||||
|
||||
/**
|
||||
* Define a required option, which must have a value after parsing. This usually means
|
||||
* the option must be specified on the command line. (Otherwise the same as .option().)
|
||||
*
|
||||
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
||||
*/
|
||||
requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;
|
||||
requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
|
||||
/** @deprecated since v7, instead use choices or a custom function */
|
||||
requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
|
||||
|
||||
/**
|
||||
* Factory routine to create a new unattached option.
|
||||
*
|
||||
* See .option() for creating an attached option, which uses this routine to
|
||||
* create the option. You can override createOption to return a custom option.
|
||||
*/
|
||||
|
||||
createOption(flags: string, description?: string): Option;
|
||||
|
||||
/**
|
||||
* Add a prepared Option.
|
||||
*
|
||||
* See .option() and .requiredOption() for creating and attaching an option in a single call.
|
||||
*/
|
||||
addOption(option: Option): this;
|
||||
|
||||
/**
|
||||
* Whether to store option values as properties on command object,
|
||||
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
storeOptionsAsProperties(): this & OptionValues;
|
||||
storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;
|
||||
storeOptionsAsProperties(storeAsProperties?: boolean): this;
|
||||
|
||||
/**
|
||||
* Alter parsing of short flags with optional values.
|
||||
*
|
||||
* @example
|
||||
* // for `.option('-f,--flag [value]'):
|
||||
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
|
||||
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
combineFlagAndOptionalValue(combine?: boolean): this;
|
||||
|
||||
/**
|
||||
* Allow unknown options on the command line.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
allowUnknownOption(allowUnknown?: boolean): this;
|
||||
|
||||
/**
|
||||
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
allowExcessArguments(allowExcess?: boolean): this;
|
||||
|
||||
/**
|
||||
* Enable positional options. Positional means global options are specified before subcommands which lets
|
||||
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
||||
*
|
||||
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
enablePositionalOptions(positional?: boolean): this;
|
||||
|
||||
/**
|
||||
* Pass through options that come after command-arguments rather than treat them as command-options,
|
||||
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
||||
* positional options to have been enabled on the program (parent commands).
|
||||
*
|
||||
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
passThroughOptions(passThrough?: boolean): this;
|
||||
|
||||
/**
|
||||
* Parse `argv`, setting options and invoking commands when defined.
|
||||
*
|
||||
* The default expectation is that the arguments are from node and have the application as argv[0]
|
||||
* and the script being run in argv[1], with user parameters after that.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* program.parse(process.argv);
|
||||
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
|
||||
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
parse(argv?: string[], options?: ParseOptions): this;
|
||||
|
||||
/**
|
||||
* Parse `argv`, setting options and invoking commands when defined.
|
||||
*
|
||||
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
|
||||
*
|
||||
* The default expectation is that the arguments are from node and have the application as argv[0]
|
||||
* and the script being run in argv[1], with user parameters after that.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* program.parseAsync(process.argv);
|
||||
* program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
|
||||
* program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
||||
*
|
||||
* @returns Promise
|
||||
*/
|
||||
parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;
|
||||
|
||||
/**
|
||||
* Parse options from `argv` removing known options,
|
||||
* and return argv split into operands and unknown arguments.
|
||||
*
|
||||
* @example
|
||||
* argv => operands, unknown
|
||||
* --known kkk op => [op], []
|
||||
* op --known kkk => [op], []
|
||||
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
||||
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
||||
*/
|
||||
parseOptions(argv: string[]): commander.ParseOptionsResult;
|
||||
|
||||
/**
|
||||
* Return an object containing options as key-value pairs
|
||||
*/
|
||||
opts(): OptionValues;
|
||||
|
||||
/**
|
||||
* Set the description.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
description(str: string, argsDescription?: {[argName: string]: string}): this;
|
||||
/**
|
||||
* Get the description.
|
||||
*/
|
||||
description(): string;
|
||||
|
||||
/**
|
||||
* Set an alias for the command.
|
||||
*
|
||||
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
alias(alias: string): this;
|
||||
/**
|
||||
* Get alias for the command.
|
||||
*/
|
||||
alias(): string;
|
||||
|
||||
/**
|
||||
* Set aliases for the command.
|
||||
*
|
||||
* Only the first alias is shown in the auto-generated help.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
aliases(aliases: string[]): this;
|
||||
/**
|
||||
* Get aliases for the command.
|
||||
*/
|
||||
aliases(): string[];
|
||||
|
||||
/**
|
||||
* Set the command usage.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
usage(str: string): this;
|
||||
/**
|
||||
* Get the command usage.
|
||||
*/
|
||||
usage(): string;
|
||||
|
||||
/**
|
||||
* Set the name of the command.
|
||||
*
|
||||
* @returns `this` command for chaining
|
||||
*/
|
||||
name(str: string): this;
|
||||
/**
|
||||
* Get the name of the command.
|
||||
*/
|
||||
name(): string;
|
||||
|
||||
/**
|
||||
* Output help information for this command.
|
||||
*
|
||||
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
||||
*
|
||||
*/
|
||||
outputHelp(context?: HelpContext): void;
|
||||
/** @deprecated since v7 */
|
||||
outputHelp(cb?: (str: string) => string): void;
|
||||
|
||||
/**
|
||||
* Return command help documentation.
|
||||
*/
|
||||
helpInformation(context?: HelpContext): string;
|
||||
|
||||
/**
|
||||
* You can pass in flags and a description to override the help
|
||||
* flags and help description for your command. Pass in false
|
||||
* to disable the built-in help option.
|
||||
*/
|
||||
helpOption(flags?: string | boolean, description?: string): this;
|
||||
|
||||
/**
|
||||
* Output help information and exit.
|
||||
*
|
||||
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
||||
*/
|
||||
help(context?: HelpContext): never;
|
||||
/** @deprecated since v7 */
|
||||
help(cb?: (str: string) => string): never;
|
||||
|
||||
/**
|
||||
* Add additional text to be displayed with the built-in help.
|
||||
*
|
||||
* Position is 'before' or 'after' to affect just this command,
|
||||
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
||||
*/
|
||||
addHelpText(position: AddHelpTextPosition, text: string): this;
|
||||
addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string | undefined): this;
|
||||
|
||||
/**
|
||||
* Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
|
||||
*/
|
||||
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
}
|
||||
type CommandConstructor = new (name?: string) => Command;
|
||||
|
||||
interface CommandOptions {
|
||||
hidden?: boolean;
|
||||
isDefault?: boolean;
|
||||
/** @deprecated since v7, replaced by hidden */
|
||||
noHelp?: boolean;
|
||||
}
|
||||
interface ExecutableCommandOptions extends CommandOptions {
|
||||
executableFile?: string;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
interface ParseOptionsResult {
|
||||
operands: string[];
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
interface CommanderStatic extends Command {
|
||||
program: Command;
|
||||
Command: CommandConstructor;
|
||||
Option: OptionConstructor;
|
||||
CommanderError: CommanderErrorConstructor;
|
||||
InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;
|
||||
Help: HelpConstructor;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Declaring namespace AND global
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
declare const commander: commander.CommanderStatic;
|
||||
export = commander;
|
||||
15
node_modules/svgo/node_modules/picocolors/LICENSE
generated
vendored
Normal file
15
node_modules/svgo/node_modules/picocolors/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2021 Alexey Raspopov, Kostiantyn Denysov, Anton Verinov
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
21
node_modules/svgo/node_modules/picocolors/README.md
generated
vendored
Normal file
21
node_modules/svgo/node_modules/picocolors/README.md
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# picocolors
|
||||
|
||||
The tiniest and the fastest library for terminal output formatting with ANSI colors.
|
||||
|
||||
```javascript
|
||||
import pc from "picocolors"
|
||||
|
||||
console.log(
|
||||
pc.green(`How are ${pc.italic(`you`)} doing?`)
|
||||
)
|
||||
```
|
||||
|
||||
- **No dependencies.**
|
||||
- **14 times** smaller and **2 times** faster than chalk.
|
||||
- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist.
|
||||
- Node.js v6+ & browsers support. Support for both CJS and ESM projects.
|
||||
- TypeScript type declarations included.
|
||||
- [`NO_COLOR`](https://no-color.org/) friendly.
|
||||
|
||||
## Docs
|
||||
Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub.
|
||||
25
node_modules/svgo/node_modules/picocolors/package.json
generated
vendored
Normal file
25
node_modules/svgo/node_modules/picocolors/package.json
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "picocolors",
|
||||
"version": "1.0.0",
|
||||
"main": "./picocolors.js",
|
||||
"types": "./picocolors.d.ts",
|
||||
"browser": {
|
||||
"./picocolors.js": "./picocolors.browser.js"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"description": "The tiniest and the fastest library for terminal output formatting with ANSI colors",
|
||||
"files": [
|
||||
"picocolors.*",
|
||||
"types.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"terminal",
|
||||
"colors",
|
||||
"formatting",
|
||||
"cli",
|
||||
"console"
|
||||
],
|
||||
"author": "Alexey Raspopov",
|
||||
"repository": "alexeyraspopov/picocolors",
|
||||
"license": "ISC"
|
||||
}
|
||||
4
node_modules/svgo/node_modules/picocolors/picocolors.browser.js
generated
vendored
Normal file
4
node_modules/svgo/node_modules/picocolors/picocolors.browser.js
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
var x=String;
|
||||
var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x}};
|
||||
module.exports=create();
|
||||
module.exports.createColors = create;
|
||||
5
node_modules/svgo/node_modules/picocolors/picocolors.d.ts
generated
vendored
Normal file
5
node_modules/svgo/node_modules/picocolors/picocolors.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Colors } from "./types"
|
||||
|
||||
declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors }
|
||||
|
||||
export = picocolors
|
||||
58
node_modules/svgo/node_modules/picocolors/picocolors.js
generated
vendored
Normal file
58
node_modules/svgo/node_modules/picocolors/picocolors.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
let tty = require("tty")
|
||||
|
||||
let isColorSupported =
|
||||
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
|
||||
("FORCE_COLOR" in process.env ||
|
||||
process.argv.includes("--color") ||
|
||||
process.platform === "win32" ||
|
||||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
|
||||
"CI" in process.env)
|
||||
|
||||
let formatter =
|
||||
(open, close, replace = open) =>
|
||||
input => {
|
||||
let string = "" + input
|
||||
let index = string.indexOf(close, open.length)
|
||||
return ~index
|
||||
? open + replaceClose(string, close, replace, index) + close
|
||||
: open + string + close
|
||||
}
|
||||
|
||||
let replaceClose = (string, close, replace, index) => {
|
||||
let start = string.substring(0, index) + replace
|
||||
let end = string.substring(index + close.length)
|
||||
let nextIndex = end.indexOf(close)
|
||||
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
|
||||
}
|
||||
|
||||
let createColors = (enabled = isColorSupported) => ({
|
||||
isColorSupported: enabled,
|
||||
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
|
||||
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
|
||||
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
|
||||
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
|
||||
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
|
||||
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
|
||||
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
|
||||
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
|
||||
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
|
||||
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
|
||||
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
|
||||
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
|
||||
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
|
||||
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
|
||||
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
|
||||
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
|
||||
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
|
||||
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
|
||||
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
|
||||
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
|
||||
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
|
||||
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
|
||||
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
|
||||
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
|
||||
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
|
||||
})
|
||||
|
||||
module.exports = createColors()
|
||||
module.exports.createColors = createColors
|
||||
30
node_modules/svgo/node_modules/picocolors/types.ts
generated
vendored
Normal file
30
node_modules/svgo/node_modules/picocolors/types.ts
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
export type Formatter = (input: string | number | null | undefined) => string
|
||||
|
||||
export interface Colors {
|
||||
isColorSupported: boolean
|
||||
reset: Formatter
|
||||
bold: Formatter
|
||||
dim: Formatter
|
||||
italic: Formatter
|
||||
underline: Formatter
|
||||
inverse: Formatter
|
||||
hidden: Formatter
|
||||
strikethrough: Formatter
|
||||
black: Formatter
|
||||
red: Formatter
|
||||
green: Formatter
|
||||
yellow: Formatter
|
||||
blue: Formatter
|
||||
magenta: Formatter
|
||||
cyan: Formatter
|
||||
white: Formatter
|
||||
gray: Formatter
|
||||
bgBlack: Formatter
|
||||
bgRed: Formatter
|
||||
bgGreen: Formatter
|
||||
bgYellow: Formatter
|
||||
bgBlue: Formatter
|
||||
bgMagenta: Formatter
|
||||
bgCyan: Formatter
|
||||
bgWhite: Formatter
|
||||
}
|
||||
126
node_modules/svgo/package.json
generated
vendored
126
node_modules/svgo/package.json
generated
vendored
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"packageManager": "yarn@2.4.3",
|
||||
"name": "svgo",
|
||||
"version": "0.6.6",
|
||||
"version": "2.8.0",
|
||||
"description": "Nodejs-based tool for optimizing SVG vector graphics files",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"svgo",
|
||||
"svg",
|
||||
@@ -10,60 +12,120 @@
|
||||
],
|
||||
"homepage": "https://github.com/svg/svgo",
|
||||
"bugs": {
|
||||
"url": "https://github.com/svg/svgo/issues",
|
||||
"email": "kir@soulshine.in"
|
||||
"url": "https://github.com/svg/svgo/issues"
|
||||
},
|
||||
"author": {
|
||||
"name": "Kir Belevich",
|
||||
"email": "kir@soulshine.in",
|
||||
"email": "kir@belevi.ch",
|
||||
"url": "https://github.com/deepsweet"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Sergey Belov",
|
||||
"email": "peimei@ya.ru",
|
||||
"url": "http://github.com/arikon"
|
||||
"url": "https://github.com/arikon"
|
||||
},
|
||||
{
|
||||
"name": "Lev Solntsev",
|
||||
"email": "lev.sun@ya.ru",
|
||||
"url": "http://github.com/GreLI"
|
||||
"url": "https://github.com/GreLI"
|
||||
},
|
||||
{
|
||||
"name": "Bogdan Chadkin",
|
||||
"email": "trysound@yandex.ru",
|
||||
"url": "https://github.com/TrySound"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/svg/svgo.git"
|
||||
},
|
||||
"main": "./lib/svgo.js",
|
||||
"bin": {
|
||||
"svgo": "./bin/svgo"
|
||||
},
|
||||
"directories": {
|
||||
"bin": "./bin",
|
||||
"lib": "./lib",
|
||||
"example": "./examples"
|
||||
"main": "./lib/svgo-node.js",
|
||||
"bin": "./bin/svgo",
|
||||
"files": [
|
||||
"bin",
|
||||
"lib",
|
||||
"plugins",
|
||||
"dist",
|
||||
"!**/*.test.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
"test": "NODE_OPTIONS=--experimental-vm-modules jest --maxWorkers=4 --coverage",
|
||||
"lint": "eslint --ignore-path .gitignore . && prettier --check \"**/*.js\" --ignore-path .gitignore",
|
||||
"fix": "eslint --ignore-path .gitignore --fix . && prettier --write \"**/*.js\" --ignore-path .gitignore",
|
||||
"typecheck": "tsc",
|
||||
"test-browser": "rollup -c && node ./test/browser.js",
|
||||
"test-regression": "node ./test/regression-extract.js && NO_DIFF=1 node ./test/regression.js",
|
||||
"prepublishOnly": "rm -rf dist && rollup -c"
|
||||
},
|
||||
"prettier": {
|
||||
"singleQuote": true
|
||||
},
|
||||
"eslintConfig": {
|
||||
"parserOptions": {
|
||||
"ecmaVersion": "2021"
|
||||
},
|
||||
"env": {
|
||||
"node": true,
|
||||
"es2021": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"rollup.config.js"
|
||||
],
|
||||
"parserOptions": {
|
||||
"sourceType": "module"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"**/*.test.js"
|
||||
],
|
||||
"env": {
|
||||
"jest": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"jest": {
|
||||
"coveragePathIgnorePatterns": [
|
||||
"fixtures"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"sax": "~1.2.1",
|
||||
"coa": "~1.0.1",
|
||||
"js-yaml": "~3.6.0",
|
||||
"colors": "~1.1.2",
|
||||
"whet.extend": "~0.9.9",
|
||||
"mkdirp": "~0.5.1",
|
||||
"csso": "~2.0.0"
|
||||
"@trysound/sax": "0.2.0",
|
||||
"commander": "^7.2.0",
|
||||
"css-select": "^4.1.3",
|
||||
"css-tree": "^1.1.3",
|
||||
"csso": "^4.2.0",
|
||||
"picocolors": "^1.0.0",
|
||||
"stable": "^0.1.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"mocha": "~2.4.5",
|
||||
"should": "8.3.1",
|
||||
"istanbul": "~0.4.3",
|
||||
"mocha-istanbul": "~0.2.0",
|
||||
"coveralls": "~2.11.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"license": "MIT"
|
||||
"@rollup/plugin-commonjs": "^20.0.0",
|
||||
"@rollup/plugin-json": "^4.1.0",
|
||||
"@rollup/plugin-node-resolve": "^13.0.4",
|
||||
"@types/css-tree": "^1.0.6",
|
||||
"@types/csso": "^4.2.0",
|
||||
"@types/jest": "^27.0.1",
|
||||
"del": "^6.0.0",
|
||||
"eslint": "^7.32.0",
|
||||
"jest": "^27.2.5",
|
||||
"node-fetch": "^2.6.2",
|
||||
"pixelmatch": "^5.2.1",
|
||||
"playwright": "^1.14.1",
|
||||
"pngjs": "^6.0.0",
|
||||
"prettier": "^2.4.0",
|
||||
"rollup": "^2.56.3",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"tar-stream": "^2.2.0",
|
||||
"typescript": "^4.4.3"
|
||||
}
|
||||
}
|
||||
|
||||
335
node_modules/svgo/plugins/_applyTransforms.js
generated
vendored
Normal file
335
node_modules/svgo/plugins/_applyTransforms.js
generated
vendored
Normal file
@@ -0,0 +1,335 @@
|
||||
'use strict';
|
||||
|
||||
// TODO implement as separate plugin
|
||||
|
||||
const {
|
||||
transformsMultiply,
|
||||
transform2js,
|
||||
transformArc,
|
||||
} = require('./_transforms.js');
|
||||
const { removeLeadingZero } = require('../lib/svgo/tools.js');
|
||||
const { referencesProps, attrsGroupsDefaults } = require('./_collections.js');
|
||||
|
||||
const regNumericValues = /[-+]?(\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
|
||||
const defaultStrokeWidth = attrsGroupsDefaults.presentation['stroke-width'];
|
||||
|
||||
/**
|
||||
* Apply transformation(s) to the Path data.
|
||||
*
|
||||
* @param {Object} elem current element
|
||||
* @param {Array} path input path data
|
||||
* @param {Object} params whether to apply transforms to stroked lines and transform precision (used for stroke width)
|
||||
* @return {Array} output path data
|
||||
*/
|
||||
const applyTransforms = (elem, pathData, params) => {
|
||||
// if there are no 'stroke' attr and references to other objects such as
|
||||
// gradiends or clip-path which are also subjects to transform.
|
||||
if (
|
||||
elem.attributes.transform == null ||
|
||||
elem.attributes.transform === '' ||
|
||||
// styles are not considered when applying transform
|
||||
// can be fixed properly with new style engine
|
||||
elem.attributes.style != null ||
|
||||
Object.entries(elem.attributes).some(
|
||||
([name, value]) =>
|
||||
referencesProps.includes(name) && value.includes('url(')
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const matrix = transformsMultiply(transform2js(elem.attributes.transform));
|
||||
const stroke = elem.computedAttr('stroke');
|
||||
const id = elem.computedAttr('id');
|
||||
const transformPrecision = params.transformPrecision;
|
||||
|
||||
if (stroke && stroke != 'none') {
|
||||
if (
|
||||
!params.applyTransformsStroked ||
|
||||
((matrix.data[0] != matrix.data[3] ||
|
||||
matrix.data[1] != -matrix.data[2]) &&
|
||||
(matrix.data[0] != -matrix.data[3] || matrix.data[1] != matrix.data[2]))
|
||||
)
|
||||
return;
|
||||
|
||||
// "stroke-width" should be inside the part with ID, otherwise it can be overrided in <use>
|
||||
if (id) {
|
||||
let idElem = elem;
|
||||
let hasStrokeWidth = false;
|
||||
|
||||
do {
|
||||
if (idElem.attributes['stroke-width']) {
|
||||
hasStrokeWidth = true;
|
||||
}
|
||||
} while (
|
||||
idElem.attributes.id !== id &&
|
||||
!hasStrokeWidth &&
|
||||
(idElem = idElem.parentNode)
|
||||
);
|
||||
|
||||
if (!hasStrokeWidth) return;
|
||||
}
|
||||
|
||||
const scale = +Math.sqrt(
|
||||
matrix.data[0] * matrix.data[0] + matrix.data[1] * matrix.data[1]
|
||||
).toFixed(transformPrecision);
|
||||
|
||||
if (scale !== 1) {
|
||||
const strokeWidth =
|
||||
elem.computedAttr('stroke-width') || defaultStrokeWidth;
|
||||
|
||||
if (
|
||||
elem.attributes['vector-effect'] == null ||
|
||||
elem.attributes['vector-effect'] !== 'non-scaling-stroke'
|
||||
) {
|
||||
if (elem.attributes['stroke-width'] != null) {
|
||||
elem.attributes['stroke-width'] = elem.attributes['stroke-width']
|
||||
.trim()
|
||||
.replace(regNumericValues, (num) => removeLeadingZero(num * scale));
|
||||
} else {
|
||||
elem.attributes['stroke-width'] = strokeWidth.replace(
|
||||
regNumericValues,
|
||||
(num) => removeLeadingZero(num * scale)
|
||||
);
|
||||
}
|
||||
|
||||
if (elem.attributes['stroke-dashoffset'] != null) {
|
||||
elem.attributes['stroke-dashoffset'] = elem.attributes[
|
||||
'stroke-dashoffset'
|
||||
]
|
||||
.trim()
|
||||
.replace(regNumericValues, (num) => removeLeadingZero(num * scale));
|
||||
}
|
||||
|
||||
if (elem.attributes['stroke-dasharray'] != null) {
|
||||
elem.attributes['stroke-dasharray'] = elem.attributes[
|
||||
'stroke-dasharray'
|
||||
]
|
||||
.trim()
|
||||
.replace(regNumericValues, (num) => removeLeadingZero(num * scale));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (id) {
|
||||
// Stroke and stroke-width can be redefined with <use>
|
||||
return;
|
||||
}
|
||||
|
||||
applyMatrixToPathData(pathData, matrix.data);
|
||||
|
||||
// remove transform attr
|
||||
delete elem.attributes.transform;
|
||||
|
||||
return;
|
||||
};
|
||||
exports.applyTransforms = applyTransforms;
|
||||
|
||||
const transformAbsolutePoint = (matrix, x, y) => {
|
||||
const newX = matrix[0] * x + matrix[2] * y + matrix[4];
|
||||
const newY = matrix[1] * x + matrix[3] * y + matrix[5];
|
||||
return [newX, newY];
|
||||
};
|
||||
|
||||
const transformRelativePoint = (matrix, x, y) => {
|
||||
const newX = matrix[0] * x + matrix[2] * y;
|
||||
const newY = matrix[1] * x + matrix[3] * y;
|
||||
return [newX, newY];
|
||||
};
|
||||
|
||||
const applyMatrixToPathData = (pathData, matrix) => {
|
||||
const start = [0, 0];
|
||||
const cursor = [0, 0];
|
||||
|
||||
for (const pathItem of pathData) {
|
||||
let { command, args } = pathItem;
|
||||
|
||||
// moveto (x y)
|
||||
if (command === 'M') {
|
||||
cursor[0] = args[0];
|
||||
cursor[1] = args[1];
|
||||
start[0] = cursor[0];
|
||||
start[1] = cursor[1];
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
if (command === 'm') {
|
||||
cursor[0] += args[0];
|
||||
cursor[1] += args[1];
|
||||
start[0] = cursor[0];
|
||||
start[1] = cursor[1];
|
||||
const [x, y] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
|
||||
// horizontal lineto (x)
|
||||
// convert to lineto to handle two-dimentional transforms
|
||||
if (command === 'H') {
|
||||
command = 'L';
|
||||
args = [args[0], cursor[1]];
|
||||
}
|
||||
if (command === 'h') {
|
||||
command = 'l';
|
||||
args = [args[0], 0];
|
||||
}
|
||||
|
||||
// vertical lineto (y)
|
||||
// convert to lineto to handle two-dimentional transforms
|
||||
if (command === 'V') {
|
||||
command = 'L';
|
||||
args = [cursor[0], args[0]];
|
||||
}
|
||||
if (command === 'v') {
|
||||
command = 'l';
|
||||
args = [0, args[0]];
|
||||
}
|
||||
|
||||
// lineto (x y)
|
||||
if (command === 'L') {
|
||||
cursor[0] = args[0];
|
||||
cursor[1] = args[1];
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
if (command === 'l') {
|
||||
cursor[0] += args[0];
|
||||
cursor[1] += args[1];
|
||||
const [x, y] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
|
||||
// curveto (x1 y1 x2 y2 x y)
|
||||
if (command === 'C') {
|
||||
cursor[0] = args[4];
|
||||
cursor[1] = args[5];
|
||||
const [x1, y1] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
const [x2, y2] = transformAbsolutePoint(matrix, args[2], args[3]);
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[4], args[5]);
|
||||
args[0] = x1;
|
||||
args[1] = y1;
|
||||
args[2] = x2;
|
||||
args[3] = y2;
|
||||
args[4] = x;
|
||||
args[5] = y;
|
||||
}
|
||||
if (command === 'c') {
|
||||
cursor[0] += args[4];
|
||||
cursor[1] += args[5];
|
||||
const [x1, y1] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
const [x2, y2] = transformRelativePoint(matrix, args[2], args[3]);
|
||||
const [x, y] = transformRelativePoint(matrix, args[4], args[5]);
|
||||
args[0] = x1;
|
||||
args[1] = y1;
|
||||
args[2] = x2;
|
||||
args[3] = y2;
|
||||
args[4] = x;
|
||||
args[5] = y;
|
||||
}
|
||||
|
||||
// smooth curveto (x2 y2 x y)
|
||||
if (command === 'S') {
|
||||
cursor[0] = args[2];
|
||||
cursor[1] = args[3];
|
||||
const [x2, y2] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[2], args[3]);
|
||||
args[0] = x2;
|
||||
args[1] = y2;
|
||||
args[2] = x;
|
||||
args[3] = y;
|
||||
}
|
||||
if (command === 's') {
|
||||
cursor[0] += args[2];
|
||||
cursor[1] += args[3];
|
||||
const [x2, y2] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
const [x, y] = transformRelativePoint(matrix, args[2], args[3]);
|
||||
args[0] = x2;
|
||||
args[1] = y2;
|
||||
args[2] = x;
|
||||
args[3] = y;
|
||||
}
|
||||
|
||||
// quadratic Bézier curveto (x1 y1 x y)
|
||||
if (command === 'Q') {
|
||||
cursor[0] = args[2];
|
||||
cursor[1] = args[3];
|
||||
const [x1, y1] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[2], args[3]);
|
||||
args[0] = x1;
|
||||
args[1] = y1;
|
||||
args[2] = x;
|
||||
args[3] = y;
|
||||
}
|
||||
if (command === 'q') {
|
||||
cursor[0] += args[2];
|
||||
cursor[1] += args[3];
|
||||
const [x1, y1] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
const [x, y] = transformRelativePoint(matrix, args[2], args[3]);
|
||||
args[0] = x1;
|
||||
args[1] = y1;
|
||||
args[2] = x;
|
||||
args[3] = y;
|
||||
}
|
||||
|
||||
// smooth quadratic Bézier curveto (x y)
|
||||
if (command === 'T') {
|
||||
cursor[0] = args[0];
|
||||
cursor[1] = args[1];
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
if (command === 't') {
|
||||
cursor[0] += args[0];
|
||||
cursor[1] += args[1];
|
||||
const [x, y] = transformRelativePoint(matrix, args[0], args[1]);
|
||||
args[0] = x;
|
||||
args[1] = y;
|
||||
}
|
||||
|
||||
// elliptical arc (rx ry x-axis-rotation large-arc-flag sweep-flag x y)
|
||||
if (command === 'A') {
|
||||
transformArc(cursor, args, matrix);
|
||||
cursor[0] = args[5];
|
||||
cursor[1] = args[6];
|
||||
// reduce number of digits in rotation angle
|
||||
if (Math.abs(args[2]) > 80) {
|
||||
const a = args[0];
|
||||
const rotation = args[2];
|
||||
args[0] = args[1];
|
||||
args[1] = a;
|
||||
args[2] = rotation + (rotation > 0 ? -90 : 90);
|
||||
}
|
||||
const [x, y] = transformAbsolutePoint(matrix, args[5], args[6]);
|
||||
args[5] = x;
|
||||
args[6] = y;
|
||||
}
|
||||
if (command === 'a') {
|
||||
transformArc([0, 0], args, matrix);
|
||||
cursor[0] += args[5];
|
||||
cursor[1] += args[6];
|
||||
// reduce number of digits in rotation angle
|
||||
if (Math.abs(args[2]) > 80) {
|
||||
const a = args[0];
|
||||
const rotation = args[2];
|
||||
args[0] = args[1];
|
||||
args[1] = a;
|
||||
args[2] = rotation + (rotation > 0 ? -90 : 90);
|
||||
}
|
||||
const [x, y] = transformRelativePoint(matrix, args[5], args[6]);
|
||||
args[5] = x;
|
||||
args[6] = y;
|
||||
}
|
||||
|
||||
// closepath
|
||||
if (command === 'z' || command === 'Z') {
|
||||
cursor[0] = start[0];
|
||||
cursor[1] = start[1];
|
||||
}
|
||||
|
||||
pathItem.command = command;
|
||||
pathItem.args = args;
|
||||
}
|
||||
};
|
||||
4525
node_modules/svgo/plugins/_collections.js
generated
vendored
4525
node_modules/svgo/plugins/_collections.js
generated
vendored
File diff suppressed because it is too large
Load Diff
1582
node_modules/svgo/plugins/_path.js
generated
vendored
1582
node_modules/svgo/plugins/_path.js
generated
vendored
File diff suppressed because it is too large
Load Diff
549
node_modules/svgo/plugins/_transforms.js
generated
vendored
549
node_modules/svgo/plugins/_transforms.js
generated
vendored
@@ -1,237 +1,298 @@
|
||||
'use strict';
|
||||
|
||||
var regTransformTypes = /matrix|translate|scale|rotate|skewX|skewY/,
|
||||
regTransformSplit = /\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/,
|
||||
regNumericValues = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
|
||||
const regTransformTypes = /matrix|translate|scale|rotate|skewX|skewY/;
|
||||
const regTransformSplit =
|
||||
/\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/;
|
||||
const regNumericValues = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
|
||||
|
||||
/**
|
||||
* @typedef {{ name: string, data: Array<number> }} TransformItem
|
||||
*/
|
||||
|
||||
/**
|
||||
* Convert transform string to JS representation.
|
||||
*
|
||||
* @param {String} transformString input string
|
||||
* @param {Object} params plugin params
|
||||
* @return {Array} output array
|
||||
* @type {(transformString: string) => Array<TransformItem>}
|
||||
*/
|
||||
exports.transform2js = function(transformString) {
|
||||
|
||||
// JS representation of the transform data
|
||||
var transforms = [],
|
||||
// current transform context
|
||||
current;
|
||||
|
||||
// split value into ['', 'translate', '10 50', '', 'scale', '2', '', 'rotate', '-45', '']
|
||||
transformString.split(regTransformSplit).forEach(function(item) {
|
||||
/*jshint -W084 */
|
||||
var num;
|
||||
|
||||
if (item) {
|
||||
// if item is a translate function
|
||||
if (regTransformTypes.test(item)) {
|
||||
// then collect it and change current context
|
||||
transforms.push(current = { name: item });
|
||||
// else if item is data
|
||||
} else {
|
||||
// then split it into [10, 50] and collect as context.data
|
||||
while (num = regNumericValues.exec(item)) {
|
||||
num = Number(num);
|
||||
if (current.data)
|
||||
current.data.push(num);
|
||||
else
|
||||
current.data = [num];
|
||||
}
|
||||
}
|
||||
exports.transform2js = (transformString) => {
|
||||
// JS representation of the transform data
|
||||
/**
|
||||
* @type {Array<TransformItem>}
|
||||
*/
|
||||
const transforms = [];
|
||||
// current transform context
|
||||
/**
|
||||
* @type {null | TransformItem}
|
||||
*/
|
||||
let current = null;
|
||||
// split value into ['', 'translate', '10 50', '', 'scale', '2', '', 'rotate', '-45', '']
|
||||
for (const item of transformString.split(regTransformSplit)) {
|
||||
var num;
|
||||
if (item) {
|
||||
// if item is a translate function
|
||||
if (regTransformTypes.test(item)) {
|
||||
// then collect it and change current context
|
||||
current = { name: item, data: [] };
|
||||
transforms.push(current);
|
||||
// else if item is data
|
||||
} else {
|
||||
// then split it into [10, 50] and collect as context.data
|
||||
// eslint-disable-next-line no-cond-assign
|
||||
while ((num = regNumericValues.exec(item))) {
|
||||
num = Number(num);
|
||||
if (current != null) {
|
||||
current.data.push(num);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return transforms;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
// return empty array if broken transform (no data)
|
||||
return current == null || current.data.length == 0 ? [] : transforms;
|
||||
};
|
||||
|
||||
/**
|
||||
* Multiply transforms into one.
|
||||
*
|
||||
* @param {Array} input transforms array
|
||||
* @return {Array} output matrix array
|
||||
* @type {(transforms: Array<TransformItem>) => TransformItem}
|
||||
*/
|
||||
exports.transformsMultiply = function(transforms) {
|
||||
|
||||
// convert transforms objects to the matrices
|
||||
transforms = transforms.map(function(transform) {
|
||||
if (transform.name === 'matrix') {
|
||||
return transform.data;
|
||||
}
|
||||
return transformToMatrix(transform);
|
||||
});
|
||||
|
||||
// multiply all matrices into one
|
||||
transforms = {
|
||||
name: 'matrix',
|
||||
data: transforms.reduce(function(a, b) {
|
||||
return multiplyTransformMatrices(a, b);
|
||||
})
|
||||
};
|
||||
|
||||
return transforms;
|
||||
|
||||
exports.transformsMultiply = (transforms) => {
|
||||
// convert transforms objects to the matrices
|
||||
const matrixData = transforms.map((transform) => {
|
||||
if (transform.name === 'matrix') {
|
||||
return transform.data;
|
||||
}
|
||||
return transformToMatrix(transform);
|
||||
});
|
||||
// multiply all matrices into one
|
||||
const matrixTransform = {
|
||||
name: 'matrix',
|
||||
data:
|
||||
matrixData.length > 0 ? matrixData.reduce(multiplyTransformMatrices) : [],
|
||||
};
|
||||
return matrixTransform;
|
||||
};
|
||||
|
||||
/**
|
||||
* Do math like a schoolgirl.
|
||||
*
|
||||
* @type {Object}
|
||||
* math utilities in radians.
|
||||
*/
|
||||
var mth = exports.mth = {
|
||||
const mth = {
|
||||
/**
|
||||
* @type {(deg: number) => number}
|
||||
*/
|
||||
rad: (deg) => {
|
||||
return (deg * Math.PI) / 180;
|
||||
},
|
||||
|
||||
rad: function(deg) {
|
||||
return deg * Math.PI / 180;
|
||||
},
|
||||
/**
|
||||
* @type {(rad: number) => number}
|
||||
*/
|
||||
deg: (rad) => {
|
||||
return (rad * 180) / Math.PI;
|
||||
},
|
||||
|
||||
deg: function(rad) {
|
||||
return rad * 180 / Math.PI;
|
||||
},
|
||||
/**
|
||||
* @type {(deg: number) => number}
|
||||
*/
|
||||
cos: (deg) => {
|
||||
return Math.cos(mth.rad(deg));
|
||||
},
|
||||
|
||||
cos: function(deg) {
|
||||
return Math.cos(this.rad(deg));
|
||||
},
|
||||
/**
|
||||
* @type {(val: number, floatPrecision: number) => number}
|
||||
*/
|
||||
acos: (val, floatPrecision) => {
|
||||
return Number(mth.deg(Math.acos(val)).toFixed(floatPrecision));
|
||||
},
|
||||
|
||||
acos: function(val, floatPrecision) {
|
||||
return +(this.deg(Math.acos(val)).toFixed(floatPrecision));
|
||||
},
|
||||
/**
|
||||
* @type {(deg: number) => number}
|
||||
*/
|
||||
sin: (deg) => {
|
||||
return Math.sin(mth.rad(deg));
|
||||
},
|
||||
|
||||
sin: function(deg) {
|
||||
return Math.sin(this.rad(deg));
|
||||
},
|
||||
/**
|
||||
* @type {(val: number, floatPrecision: number) => number}
|
||||
*/
|
||||
asin: (val, floatPrecision) => {
|
||||
return Number(mth.deg(Math.asin(val)).toFixed(floatPrecision));
|
||||
},
|
||||
|
||||
asin: function(val, floatPrecision) {
|
||||
return +(this.deg(Math.asin(val)).toFixed(floatPrecision));
|
||||
},
|
||||
|
||||
tan: function(deg) {
|
||||
return Math.tan(this.rad(deg));
|
||||
},
|
||||
|
||||
atan: function(val, floatPrecision) {
|
||||
return +(this.deg(Math.atan(val)).toFixed(floatPrecision));
|
||||
}
|
||||
/**
|
||||
* @type {(deg: number) => number}
|
||||
*/
|
||||
tan: (deg) => {
|
||||
return Math.tan(mth.rad(deg));
|
||||
},
|
||||
|
||||
/**
|
||||
* @type {(val: number, floatPrecision: number) => number}
|
||||
*/
|
||||
atan: (val, floatPrecision) => {
|
||||
return Number(mth.deg(Math.atan(val)).toFixed(floatPrecision));
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* convertToShorts: boolean,
|
||||
* floatPrecision: number,
|
||||
* transformPrecision: number,
|
||||
* matrixToTransform: boolean,
|
||||
* shortTranslate: boolean,
|
||||
* shortScale: boolean,
|
||||
* shortRotate: boolean,
|
||||
* removeUseless: boolean,
|
||||
* collapseIntoOne: boolean,
|
||||
* leadingZero: boolean,
|
||||
* negativeExtraSpace: boolean,
|
||||
* }} TransformParams
|
||||
*/
|
||||
|
||||
/**
|
||||
* Decompose matrix into simple transforms. See
|
||||
* http://www.maths-informatique-jeux.com/blog/frederic/?post/2013/12/01/Decomposition-of-2D-transform-matrices
|
||||
* https://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
|
||||
*
|
||||
* @param {Object} data matrix transform object
|
||||
* @return {Object|Array} transforms array or original transform object
|
||||
* @type {(transform: TransformItem, params: TransformParams) => Array<TransformItem>}
|
||||
*/
|
||||
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),
|
||||
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);
|
||||
exports.matrixToTransform = (transform, params) => {
|
||||
let floatPrecision = params.floatPrecision;
|
||||
let data = transform.data;
|
||||
let transforms = [];
|
||||
let sx = Number(
|
||||
Math.hypot(data[0], data[1]).toFixed(params.transformPrecision)
|
||||
);
|
||||
let sy = Number(
|
||||
((data[0] * data[3] - data[1] * data[2]) / sx).toFixed(
|
||||
params.transformPrecision
|
||||
)
|
||||
);
|
||||
let colsSum = data[0] * data[2] + data[1] * data[3];
|
||||
let rowsSum = data[0] * data[1] + data[2] * data[3];
|
||||
let scaleBefore = rowsSum != 0 || sx == sy;
|
||||
|
||||
// [..., ..., ..., ..., tx, ty] → translate(tx, ty)
|
||||
if (data[4] || data[5]) {
|
||||
transforms.push({ name: 'translate', data: data.slice(4, data[5] ? 6 : 5) });
|
||||
}
|
||||
// [..., ..., ..., ..., tx, ty] → translate(tx, ty)
|
||||
if (data[4] || data[5]) {
|
||||
transforms.push({
|
||||
name: 'translate',
|
||||
data: data.slice(4, data[5] ? 6 : 5),
|
||||
});
|
||||
}
|
||||
|
||||
// [sx, 0, tan(a)·sy, sy, 0, 0] → skewX(a)·scale(sx, sy)
|
||||
if (!data[1] && data[2]) {
|
||||
transforms.push({ name: 'skewX', data: [mth.atan(data[2] / sy, floatPrecision)] });
|
||||
// [sx, 0, tan(a)·sy, sy, 0, 0] → skewX(a)·scale(sx, sy)
|
||||
if (!data[1] && data[2]) {
|
||||
transforms.push({
|
||||
name: 'skewX',
|
||||
data: [mth.atan(data[2] / sy, floatPrecision)],
|
||||
});
|
||||
|
||||
// [sx, sx·tan(a), 0, sy, 0, 0] → skewY(a)·scale(sx, sy)
|
||||
} else if (data[1] && !data[2]) {
|
||||
transforms.push({ name: 'skewY', data: [mth.atan(data[1] / data[0], floatPrecision)] });
|
||||
sx = data[0];
|
||||
sy = data[3];
|
||||
} else if (data[1] && !data[2]) {
|
||||
transforms.push({
|
||||
name: 'skewY',
|
||||
data: [mth.atan(data[1] / data[0], floatPrecision)],
|
||||
});
|
||||
sx = data[0];
|
||||
sy = data[3];
|
||||
|
||||
// [sx·cos(a), sx·sin(a), sy·-sin(a), sy·cos(a), x, y] → rotate(a[, cx, cy])·(scale or skewX) or
|
||||
// [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]);
|
||||
transforms.push({ name: 'scale', data: [sx, sy] });
|
||||
}
|
||||
var rotate = [mth.acos(data[0] / sx, floatPrecision) * (data[1] * sy < 0 ? -1 : 1)];
|
||||
} else if (!colsSum || (sx == 1 && sy == 1) || !scaleBefore) {
|
||||
if (!scaleBefore) {
|
||||
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 angle = Math.min(Math.max(-1, data[0] / sx), 1),
|
||||
rotate = [
|
||||
mth.acos(angle, floatPrecision) *
|
||||
((scaleBefore ? 1 : sy) * data[1] < 0 ? -1 : 1),
|
||||
];
|
||||
|
||||
if (rotate[0]) transforms.push({ name: 'rotate', data: rotate });
|
||||
if (rotate[0]) transforms.push({ name: 'rotate', data: rotate });
|
||||
|
||||
if (rowsSum && colsSum) transforms.push({
|
||||
name: 'skewX',
|
||||
data: [mth.atan(colsSum / (sx * sx), floatPrecision)]
|
||||
});
|
||||
if (rowsSum && colsSum)
|
||||
transforms.push({
|
||||
name: 'skewX',
|
||||
data: [mth.atan(colsSum / (sx * sx), floatPrecision)],
|
||||
});
|
||||
|
||||
// rotate(a, cx, cy) can consume translate() within optional arguments cx, cy (rotation point)
|
||||
if (rotate[0] && (data[4] || data[5])) {
|
||||
transforms.shift();
|
||||
var cos = data[0] / sx,
|
||||
sin = data[1] / (scaleBefore ? sx : sy),
|
||||
x = data[4] * (scaleBefore || sy),
|
||||
y = data[5] * (scaleBefore || sx),
|
||||
denom = (Math.pow(1 - cos, 2) + Math.pow(sin, 2)) * (scaleBefore || sx * sy);
|
||||
rotate.push(((1 - cos) * x - sin * y) / denom);
|
||||
rotate.push(((1 - cos) * y + sin * x) / denom);
|
||||
}
|
||||
|
||||
// Too many transformations, return original matrix if it isn't just a scale/translate
|
||||
} else if (data[1] || data[2]) {
|
||||
return transform;
|
||||
// rotate(a, cx, cy) can consume translate() within optional arguments cx, cy (rotation point)
|
||||
if (rotate[0] && (data[4] || data[5])) {
|
||||
transforms.shift();
|
||||
var cos = data[0] / sx,
|
||||
sin = data[1] / (scaleBefore ? sx : sy),
|
||||
x = data[4] * (scaleBefore ? 1 : sy),
|
||||
y = data[5] * (scaleBefore ? 1 : sx),
|
||||
denom =
|
||||
(Math.pow(1 - cos, 2) + Math.pow(sin, 2)) *
|
||||
(scaleBefore ? 1 : sx * sy);
|
||||
rotate.push(((1 - cos) * x - sin * y) / denom);
|
||||
rotate.push(((1 - cos) * y + sin * x) / denom);
|
||||
}
|
||||
|
||||
if (scaleBefore && (sx != 1 || sy != 1) || !transforms.length) transforms.push({
|
||||
name: 'scale',
|
||||
data: sx == sy ? [sx] : [sx, sy]
|
||||
// Too many transformations, return original matrix if it isn't just a scale/translate
|
||||
} else if (data[1] || data[2]) {
|
||||
return [transform];
|
||||
}
|
||||
|
||||
if ((scaleBefore && (sx != 1 || sy != 1)) || !transforms.length)
|
||||
transforms.push({
|
||||
name: 'scale',
|
||||
data: sx == sy ? [sx] : [sx, sy],
|
||||
});
|
||||
|
||||
return transforms;
|
||||
return transforms;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert transform to the matrix data.
|
||||
*
|
||||
* @param {Object} transform transform object
|
||||
* @return {Array} matrix data
|
||||
* @type {(transform: TransformItem) => Array<number> }
|
||||
*/
|
||||
function transformToMatrix(transform) {
|
||||
|
||||
if (transform.name === 'matrix') return transform.data;
|
||||
|
||||
var matrix;
|
||||
|
||||
switch (transform.name) {
|
||||
case 'translate':
|
||||
// [1, 0, 0, 1, tx, ty]
|
||||
matrix = [1, 0, 0, 1, transform.data[0], transform.data[1] || 0];
|
||||
break;
|
||||
case 'scale':
|
||||
// [sx, 0, 0, sy, 0, 0]
|
||||
matrix = [transform.data[0], 0, 0, transform.data[1] || transform.data[0], 0, 0];
|
||||
break;
|
||||
case 'rotate':
|
||||
// [cos(a), sin(a), -sin(a), cos(a), x, y]
|
||||
var cos = mth.cos(transform.data[0]),
|
||||
sin = mth.sin(transform.data[0]),
|
||||
cx = transform.data[1] || 0,
|
||||
cy = transform.data[2] || 0;
|
||||
|
||||
matrix = [cos, sin, -sin, cos, (1 - cos) * cx + sin * cy, (1 - cos) * cy - sin * cx];
|
||||
break;
|
||||
case 'skewX':
|
||||
// [1, 0, tan(a), 1, 0, 0]
|
||||
matrix = [1, 0, mth.tan(transform.data[0]), 1, 0, 0];
|
||||
break;
|
||||
case 'skewY':
|
||||
// [1, tan(a), 0, 1, 0, 0]
|
||||
matrix = [1, mth.tan(transform.data[0]), 0, 1, 0, 0];
|
||||
break;
|
||||
}
|
||||
|
||||
return matrix;
|
||||
|
||||
}
|
||||
const transformToMatrix = (transform) => {
|
||||
if (transform.name === 'matrix') {
|
||||
return transform.data;
|
||||
}
|
||||
switch (transform.name) {
|
||||
case 'translate':
|
||||
// [1, 0, 0, 1, tx, ty]
|
||||
return [1, 0, 0, 1, transform.data[0], transform.data[1] || 0];
|
||||
case 'scale':
|
||||
// [sx, 0, 0, sy, 0, 0]
|
||||
return [
|
||||
transform.data[0],
|
||||
0,
|
||||
0,
|
||||
transform.data[1] || transform.data[0],
|
||||
0,
|
||||
0,
|
||||
];
|
||||
case 'rotate':
|
||||
// [cos(a), sin(a), -sin(a), cos(a), x, y]
|
||||
var cos = mth.cos(transform.data[0]),
|
||||
sin = mth.sin(transform.data[0]),
|
||||
cx = transform.data[1] || 0,
|
||||
cy = transform.data[2] || 0;
|
||||
return [
|
||||
cos,
|
||||
sin,
|
||||
-sin,
|
||||
cos,
|
||||
(1 - cos) * cx + sin * cy,
|
||||
(1 - cos) * cy - sin * cx,
|
||||
];
|
||||
case 'skewX':
|
||||
// [1, 0, tan(a), 1, 0, 0]
|
||||
return [1, 0, mth.tan(transform.data[0]), 1, 0, 0];
|
||||
case 'skewY':
|
||||
// [1, tan(a), 0, 1, 0, 0]
|
||||
return [1, mth.tan(transform.data[0]), 0, 1, 0, 0];
|
||||
default:
|
||||
throw Error(`Unknown transform ${transform.name}`);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies transformation to an arc. To do so, we represent ellipse as a matrix, multiply it
|
||||
@@ -239,70 +300,80 @@ function transformToMatrix(transform) {
|
||||
* rotate(θ)·scale(a b)·rotate(φ). This gives us new ellipse params a, b and θ.
|
||||
* SVD is being done with the formulae provided by Wolffram|Alpha (svd {{m0, m2}, {m1, m3}})
|
||||
*
|
||||
* @param {Array} arc [a, b, rotation in deg]
|
||||
* @param {Array} transform transformation matrix
|
||||
* @return {Array} arc transformed input arc
|
||||
* @type {(
|
||||
* cursor: [x: number, y: number],
|
||||
* arc: Array<number>,
|
||||
* transform: Array<number>
|
||||
* ) => Array<number>}
|
||||
*/
|
||||
exports.transformArc = function(arc, transform) {
|
||||
|
||||
var a = arc[0],
|
||||
b = arc[1],
|
||||
rot = arc[2] * Math.PI / 180,
|
||||
cos = Math.cos(rot),
|
||||
sin = Math.sin(rot),
|
||||
h = Math.pow(arc[5] * cos + arc[6] * sin, 2) / (4 * a * a) +
|
||||
Math.pow(arc[6] * cos - arc[5] * sin, 2) / (4 * b * b);
|
||||
exports.transformArc = (cursor, arc, transform) => {
|
||||
const x = arc[5] - cursor[0];
|
||||
const y = arc[6] - cursor[1];
|
||||
let a = arc[0];
|
||||
let b = arc[1];
|
||||
const rot = (arc[2] * Math.PI) / 180;
|
||||
const cos = Math.cos(rot);
|
||||
const sin = Math.sin(rot);
|
||||
// skip if radius is 0
|
||||
if (a > 0 && b > 0) {
|
||||
let h =
|
||||
Math.pow(x * cos + y * sin, 2) / (4 * a * a) +
|
||||
Math.pow(y * cos - x * sin, 2) / (4 * b * b);
|
||||
if (h > 1) {
|
||||
h = Math.sqrt(h);
|
||||
a *= h;
|
||||
b *= h;
|
||||
h = Math.sqrt(h);
|
||||
a *= h;
|
||||
b *= h;
|
||||
}
|
||||
var ellipse = [a * cos, a * sin, -b * sin, b * cos, 0, 0],
|
||||
m = multiplyTransformMatrices(transform, ellipse),
|
||||
// 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))
|
||||
);
|
||||
}
|
||||
const ellipse = [a * cos, a * sin, -b * sin, b * cos, 0, 0];
|
||||
const m = multiplyTransformMatrices(transform, ellipse);
|
||||
// Decompose the new ellipse matrix
|
||||
const lastCol = m[2] * m[2] + m[3] * m[3];
|
||||
const squareSum = m[0] * m[0] + m[1] * m[1] + lastCol;
|
||||
const 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);
|
||||
arc[2] = 0;
|
||||
} else {
|
||||
var majorAxisSqr = (squareSum + root) / 2,
|
||||
minorAxisSqr = (squareSum - root) / 2,
|
||||
major = Math.abs(majorAxisSqr - lastCol) > 1e-6,
|
||||
sub = (major ? majorAxisSqr : minorAxisSqr) - lastCol,
|
||||
rowsSum = m[0] * m[2] + m[1] * m[3],
|
||||
term1 = m[0] * sub + m[2] * rowsSum,
|
||||
term2 = m[1] * sub + m[3] * rowsSum;
|
||||
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;
|
||||
}
|
||||
return arc;
|
||||
if (!root) {
|
||||
// circle
|
||||
arc[0] = arc[1] = Math.sqrt(squareSum / 2);
|
||||
arc[2] = 0;
|
||||
} else {
|
||||
const majorAxisSqr = (squareSum + root) / 2;
|
||||
const minorAxisSqr = (squareSum - root) / 2;
|
||||
const major = Math.abs(majorAxisSqr - lastCol) > 1e-6;
|
||||
const sub = (major ? majorAxisSqr : minorAxisSqr) - lastCol;
|
||||
const rowsSum = m[0] * m[2] + m[1] * m[3];
|
||||
const term1 = m[0] * sub + m[2] * rowsSum;
|
||||
const term2 = m[1] * sub + m[3] * rowsSum;
|
||||
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.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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Multiply transformation matrices.
|
||||
*
|
||||
* @param {Array} a matrix A data
|
||||
* @param {Array} b matrix B data
|
||||
* @return {Array} result
|
||||
* @type {(a: Array<number>, b: Array<number>) => Array<number>}
|
||||
*/
|
||||
function multiplyTransformMatrices(a, b) {
|
||||
|
||||
return [
|
||||
a[0] * b[0] + a[2] * b[1],
|
||||
a[1] * b[0] + a[3] * b[1],
|
||||
a[0] * b[2] + a[2] * b[3],
|
||||
a[1] * b[2] + a[3] * b[3],
|
||||
a[0] * b[4] + a[2] * b[5] + a[4],
|
||||
a[1] * b[4] + a[3] * b[5] + a[5]
|
||||
];
|
||||
|
||||
}
|
||||
const multiplyTransformMatrices = (a, b) => {
|
||||
return [
|
||||
a[0] * b[0] + a[2] * b[1],
|
||||
a[1] * b[0] + a[3] * b[1],
|
||||
a[0] * b[2] + a[2] * b[3],
|
||||
a[1] * b[2] + a[3] * b[3],
|
||||
a[0] * b[4] + a[2] * b[5] + a[4],
|
||||
a[1] * b[4] + a[3] * b[5] + a[5],
|
||||
];
|
||||
};
|
||||
|
||||
87
node_modules/svgo/plugins/addAttributesToSVGElement.js
generated
vendored
Normal file
87
node_modules/svgo/plugins/addAttributesToSVGElement.js
generated
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
exports.name = 'addAttributesToSVGElement';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
exports.description = 'adds attributes to an outer <svg> element';
|
||||
|
||||
var ENOCLS = `Error in plugin "addAttributesToSVGElement": absent parameters.
|
||||
It should have a list of "attributes" or one "attribute".
|
||||
Config example:
|
||||
|
||||
plugins: [
|
||||
{
|
||||
name: 'addAttributesToSVGElement',
|
||||
params: {
|
||||
attribute: "mySvg"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
plugins: [
|
||||
{
|
||||
name: 'addAttributesToSVGElement',
|
||||
params: {
|
||||
attributes: ["mySvg", "size-big"]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
plugins: [
|
||||
{
|
||||
name: 'addAttributesToSVGElement',
|
||||
params: {
|
||||
attributes: [
|
||||
{
|
||||
focusable: false
|
||||
},
|
||||
{
|
||||
'data-image': icon
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
`;
|
||||
|
||||
/**
|
||||
* Add attributes to an outer <svg> element. Example config:
|
||||
*
|
||||
* @author April Arcus
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* attribute?: string | Record<string, null | string>,
|
||||
* attributes?: Array<string | Record<string, null | string>>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = (root, params) => {
|
||||
if (!Array.isArray(params.attributes) && !params.attribute) {
|
||||
console.error(ENOCLS);
|
||||
return null;
|
||||
}
|
||||
const attributes = params.attributes || [params.attribute];
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
for (const attribute of attributes) {
|
||||
if (typeof attribute === 'string') {
|
||||
if (node.attributes[attribute] == null) {
|
||||
// @ts-ignore disallow explicit nullable attribute value
|
||||
node.attributes[attribute] = undefined;
|
||||
}
|
||||
}
|
||||
if (typeof attribute === 'object') {
|
||||
for (const key of Object.keys(attribute)) {
|
||||
if (node.attributes[key] == null) {
|
||||
// @ts-ignore disallow explicit nullable attribute value
|
||||
node.attributes[key] = attribute[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
119
node_modules/svgo/plugins/addClassesToSVGElement.js
generated
vendored
119
node_modules/svgo/plugins/addClassesToSVGElement.js
generated
vendored
@@ -1,62 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'full';
|
||||
|
||||
exports.name = 'addClassesToSVGElement';
|
||||
exports.type = 'visitor';
|
||||
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: [
|
||||
{
|
||||
name: "addClassesToSVGElement",
|
||||
params: {
|
||||
className: "mySvg"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
plugins: [
|
||||
{
|
||||
name: "addClassesToSVGElement",
|
||||
params: {
|
||||
classNames: ["mySvg", "size-big"]
|
||||
}
|
||||
}
|
||||
]
|
||||
`;
|
||||
|
||||
/**
|
||||
* Add classnames to an outer <svg> element. Example config:
|
||||
*
|
||||
* plugins:
|
||||
* - addClassesToSVGElement:
|
||||
* className: 'mySvg'
|
||||
* plugins: [
|
||||
* {
|
||||
* name: "addClassesToSVGElement",
|
||||
* params: {
|
||||
* className: "mySvg"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* plugins:
|
||||
* - addClassesToSVGElement:
|
||||
* classNames: ['mySvg', 'size-big']
|
||||
* plugins: [
|
||||
* {
|
||||
* name: "addClassesToSVGElement",
|
||||
* params: {
|
||||
* classNames: ["mySvg", "size-big"]
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* @author April Arcus
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* className?: string,
|
||||
* classNames?: Array<string>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(data, params) {
|
||||
if (!params || !(Array.isArray(params.classNames) && params.classNames.some(String) || params.className)) {
|
||||
console.error(ENOCLS);
|
||||
return data;
|
||||
}
|
||||
|
||||
var classNames = params.classNames || [ params.className ],
|
||||
svg = data.content[0];
|
||||
|
||||
if (svg.isElem('svg')) {
|
||||
if (svg.hasAttr('class')) {
|
||||
svg.attr('class').value =
|
||||
svg.attr('class').value
|
||||
.split(' ')
|
||||
.concat(classNames)
|
||||
.join(' ');
|
||||
} else {
|
||||
svg.addAttr({
|
||||
name: 'class',
|
||||
value: classNames.join(' '),
|
||||
prefix: '',
|
||||
local: 'class'
|
||||
});
|
||||
exports.fn = (root, params) => {
|
||||
if (
|
||||
!(Array.isArray(params.classNames) && params.classNames.some(String)) &&
|
||||
!params.className
|
||||
) {
|
||||
console.error(ENOCLS);
|
||||
return null;
|
||||
}
|
||||
const classNames = params.classNames || [params.className];
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
const classList = new Set(
|
||||
node.attributes.class == null
|
||||
? null
|
||||
: node.attributes.class.split(' ')
|
||||
);
|
||||
for (const className of classNames) {
|
||||
if (className != null) {
|
||||
classList.add(className);
|
||||
}
|
||||
}
|
||||
node.attributes.class = Array.from(classList).join(' ');
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
89
node_modules/svgo/plugins/cleanupAttrs.js
generated
vendored
89
node_modules/svgo/plugins/cleanupAttrs.js
generated
vendored
@@ -1,56 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.name = 'cleanupAttrs';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
exports.description =
|
||||
'cleanups attributes from newlines, trailing and repeating spaces';
|
||||
|
||||
exports.description = 'cleanups attributes from newlines, trailing and repeating spaces';
|
||||
|
||||
exports.params = {
|
||||
newlines: true,
|
||||
trim: true,
|
||||
spaces: true
|
||||
};
|
||||
|
||||
var regNewlinesNeedSpace = /(\S)\n(\S)/g,
|
||||
regNewlines = /\n/g,
|
||||
regSpaces = /\s{2,}/g;
|
||||
const regNewlinesNeedSpace = /(\S)\r?\n(\S)/g;
|
||||
const regNewlines = /\r?\n/g;
|
||||
const regSpaces = /\s{2,}/g;
|
||||
|
||||
/**
|
||||
* Cleanup attributes values from newlines, trailing and repeating spaces.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* newlines?: boolean,
|
||||
* trim?: boolean,
|
||||
* spaces?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
|
||||
if (item.isElem()) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
|
||||
if (params.newlines) {
|
||||
// new line which requires a space instead of themselve
|
||||
attr.value = attr.value.replace(regNewlinesNeedSpace, function(match, p1, p2) {
|
||||
return p1 + ' ' + p2;
|
||||
});
|
||||
|
||||
// simple new line
|
||||
attr.value = attr.value.replace(regNewlines, '');
|
||||
}
|
||||
|
||||
if (params.trim) {
|
||||
attr.value = attr.value.trim();
|
||||
}
|
||||
|
||||
if (params.spaces) {
|
||||
attr.value = attr.value.replace(regSpaces, ' ');
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
exports.fn = (root, params) => {
|
||||
const { newlines = true, trim = true, spaces = true } = params;
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (newlines) {
|
||||
// new line which requires a space instead of themselve
|
||||
node.attributes[name] = node.attributes[name].replace(
|
||||
regNewlinesNeedSpace,
|
||||
(match, p1, p2) => p1 + ' ' + p2
|
||||
);
|
||||
// simple new line
|
||||
node.attributes[name] = node.attributes[name].replace(
|
||||
regNewlines,
|
||||
''
|
||||
);
|
||||
}
|
||||
if (trim) {
|
||||
node.attributes[name] = node.attributes[name].trim();
|
||||
}
|
||||
if (spaces) {
|
||||
node.attributes[name] = node.attributes[name].replace(
|
||||
regSpaces,
|
||||
' '
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
117
node_modules/svgo/plugins/cleanupEnableBackground.js
generated
vendored
117
node_modules/svgo/plugins/cleanupEnableBackground.js
generated
vendored
@@ -1,84 +1,75 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'full';
|
||||
const { visit } = require('../lib/xast.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'cleanupEnableBackground';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'remove or cleanup enable-background attribute when possible';
|
||||
exports.description =
|
||||
'remove or cleanup enable-background attribute when possible';
|
||||
|
||||
/**
|
||||
* Remove or cleanup enable-background attr which coincides with a width/height box.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/filters.html#EnableBackgroundProperty
|
||||
* @see https://www.w3.org/TR/SVG11/filters.html#EnableBackgroundProperty
|
||||
*
|
||||
* @example
|
||||
* <svg width="100" height="50" enable-background="new 0 0 100 50">
|
||||
* ⬇
|
||||
* <svg width="100" height="50">
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(data) {
|
||||
exports.fn = (root) => {
|
||||
const regEnableBackground =
|
||||
/^new\s0\s0\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)$/;
|
||||
|
||||
var regEnableBackground = /^new\s0\s0\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)$/,
|
||||
hasFilter = false,
|
||||
elems = ['svg', 'mask', 'pattern'];
|
||||
let hasFilter = false;
|
||||
visit(root, {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.name === 'filter') {
|
||||
hasFilter = true;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function checkEnableBackground(item) {
|
||||
if (
|
||||
item.isElem(elems) &&
|
||||
item.hasAttr('enable-background') &&
|
||||
item.hasAttr('width') &&
|
||||
item.hasAttr('height')
|
||||
) {
|
||||
|
||||
var match = item.attr('enable-background').value.match(regEnableBackground);
|
||||
|
||||
if (match) {
|
||||
if (
|
||||
item.attr('width').value === match[1] &&
|
||||
item.attr('height').value === match[3]
|
||||
) {
|
||||
if (item.isElem('svg')) {
|
||||
item.removeAttr('enable-background');
|
||||
} else {
|
||||
item.attr('enable-background').value = 'new';
|
||||
}
|
||||
}
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.attributes['enable-background'] == null) {
|
||||
return;
|
||||
}
|
||||
if (hasFilter) {
|
||||
if (
|
||||
(node.name === 'svg' ||
|
||||
node.name === 'mask' ||
|
||||
node.name === 'pattern') &&
|
||||
node.attributes.width != null &&
|
||||
node.attributes.height != null
|
||||
) {
|
||||
const match =
|
||||
node.attributes['enable-background'].match(regEnableBackground);
|
||||
if (
|
||||
match != null &&
|
||||
node.attributes.width === match[1] &&
|
||||
node.attributes.height === match[3]
|
||||
) {
|
||||
if (node.name === 'svg') {
|
||||
delete node.attributes['enable-background'];
|
||||
} else {
|
||||
node.attributes['enable-background'] = 'new';
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
//we don't need 'enable-background' if we have no filters
|
||||
delete node.attributes['enable-background'];
|
||||
}
|
||||
}
|
||||
|
||||
function checkForFilter(item) {
|
||||
if (item.isElem('filter')) {
|
||||
hasFilter = true;
|
||||
}
|
||||
}
|
||||
|
||||
function monkeys(items, fn) {
|
||||
items.content.forEach(function(item) {
|
||||
fn(item);
|
||||
|
||||
if (item.content) {
|
||||
monkeys(item, fn);
|
||||
}
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
var firstStep = monkeys(data, function(item) {
|
||||
checkEnableBackground(item);
|
||||
if (!hasFilter) {
|
||||
checkForFilter(item);
|
||||
}
|
||||
});
|
||||
|
||||
return hasFilter ? firstStep : monkeys(firstStep, function(item) {
|
||||
//we don't need 'enable-background' if we have no filters
|
||||
item.removeAttr('enable-background');
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
451
node_modules/svgo/plugins/cleanupIDs.js
generated
vendored
451
node_modules/svgo/plugins/cleanupIDs.js
generated
vendored
@@ -1,208 +1,297 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'full';
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
*/
|
||||
|
||||
const { visitSkip } = require('../lib/xast.js');
|
||||
const { referencesProps } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'cleanupIDs';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes unused IDs and minifies used';
|
||||
|
||||
exports.params = {
|
||||
remove: true,
|
||||
minify: true,
|
||||
prefix: ''
|
||||
};
|
||||
|
||||
var referencesProps = require('./_collections').referencesProps,
|
||||
regReferencesUrl = /\burl\(("|')?#(.+?)\1\)/,
|
||||
regReferencesHref = /^#(.+?)$/,
|
||||
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',
|
||||
'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'
|
||||
],
|
||||
maxIDindex = generateIDchars.length - 1;
|
||||
const regReferencesUrl = /\burl\(("|')?#(.+?)\1\)/;
|
||||
const regReferencesHref = /^#(.+?)$/;
|
||||
const regReferencesBegin = /(\w+)\./;
|
||||
const 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',
|
||||
'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',
|
||||
];
|
||||
const maxIDindex = generateIDchars.length - 1;
|
||||
|
||||
/**
|
||||
* Remove unused and minify used IDs
|
||||
* (only if there are no any <style> or <script>).
|
||||
* Check if an ID starts with any one of a list of strings.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
*
|
||||
* @author Kir Belevich
|
||||
* @type {(string: string, prefixes: Array<string>) => boolean}
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* Bananas!
|
||||
*
|
||||
* @param {Array} items input items
|
||||
* @return {Array} output items
|
||||
*/
|
||||
function monkeys(items) {
|
||||
|
||||
for (var i = 0; i < items.content.length && !hasStyleOrScript; i++) {
|
||||
|
||||
var item = items.content[i],
|
||||
match;
|
||||
|
||||
// check if <style> of <script> presents
|
||||
if (item.isElem(styleOrScript)) {
|
||||
hasStyleOrScript = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// …and don't remove any ID if yes
|
||||
if (item.isElem()) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
var key;
|
||||
// save IDs
|
||||
if (attr.name === 'id') {
|
||||
key = idPrefix + attr.value;
|
||||
if (key in IDs) {
|
||||
item.removeAttr('id');
|
||||
} else {
|
||||
IDs[key] = item;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (
|
||||
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];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// go deeper
|
||||
if (item.content) {
|
||||
monkeys(item);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
|
||||
const hasStringPrefix = (string, prefixes) => {
|
||||
for (const prefix of prefixes) {
|
||||
if (string.startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
data = monkeys(data);
|
||||
|
||||
if (hasStyleOrScript) {
|
||||
return data;
|
||||
}
|
||||
|
||||
for (var k in referencesIDs) {
|
||||
if (IDs[k]) {
|
||||
|
||||
// replace referenced IDs with the minified ones
|
||||
if (params.minify) {
|
||||
|
||||
currentIDstring = getIDstring(currentID = generateID(currentID), params);
|
||||
IDs[k].attr('id').value = currentIDstring;
|
||||
|
||||
referencesIDs[k].forEach(function(attr) {
|
||||
k = k.replace(idPrefix, '');
|
||||
attr.value = attr.value
|
||||
.replace('#' + k, '#' + currentIDstring)
|
||||
.replace(k + '.', currentIDstring + '.');
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// don't remove referenced IDs
|
||||
delete IDs[idPrefix + k];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// remove non-referenced IDs attributes from elements
|
||||
if (params.remove) {
|
||||
|
||||
for(var ID in IDs) {
|
||||
IDs[ID].removeAttr('id');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate unique minimal ID.
|
||||
*
|
||||
* @param {Array} [currentID] current ID
|
||||
* @return {Array} generated ID array
|
||||
* @type {(currentID: null | Array<number>) => Array<number>}
|
||||
*/
|
||||
function generateID(currentID) {
|
||||
|
||||
if (!currentID) return [0];
|
||||
|
||||
currentID[currentID.length - 1]++;
|
||||
|
||||
for(var i = currentID.length - 1; i > 0; i--) {
|
||||
if (currentID[i] > maxIDindex) {
|
||||
currentID[i] = 0;
|
||||
|
||||
if (currentID[i - 1] !== undefined) {
|
||||
currentID[i - 1]++;
|
||||
}
|
||||
}
|
||||
const generateID = (currentID) => {
|
||||
if (currentID == null) {
|
||||
return [0];
|
||||
}
|
||||
currentID[currentID.length - 1] += 1;
|
||||
for (let i = currentID.length - 1; i > 0; i--) {
|
||||
if (currentID[i] > maxIDindex) {
|
||||
currentID[i] = 0;
|
||||
if (currentID[i - 1] !== undefined) {
|
||||
currentID[i - 1]++;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentID[0] > maxIDindex) {
|
||||
currentID[0] = 0;
|
||||
currentID.unshift(0);
|
||||
}
|
||||
|
||||
return currentID;
|
||||
|
||||
}
|
||||
}
|
||||
if (currentID[0] > maxIDindex) {
|
||||
currentID[0] = 0;
|
||||
currentID.unshift(0);
|
||||
}
|
||||
return currentID;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get string from generated ID array.
|
||||
*
|
||||
* @param {Array} arr input ID array
|
||||
* @return {String} output ID string
|
||||
* @type {(arr: Array<number>, prefix: string) => string}
|
||||
*/
|
||||
function getIDstring(arr, params) {
|
||||
const getIDstring = (arr, prefix) => {
|
||||
return prefix + arr.map((i) => generateIDchars[i]).join('');
|
||||
};
|
||||
|
||||
var str = params.prefix;
|
||||
/**
|
||||
* Remove unused and minify used IDs
|
||||
* (only if there are no any <style> or <script>).
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* remove?: boolean,
|
||||
* minify?: boolean,
|
||||
* prefix?: string,
|
||||
* preserve?: Array<string>,
|
||||
* preservePrefixes?: Array<string>,
|
||||
* force?: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = (_root, params) => {
|
||||
const {
|
||||
remove = true,
|
||||
minify = true,
|
||||
prefix = '',
|
||||
preserve = [],
|
||||
preservePrefixes = [],
|
||||
force = false,
|
||||
} = params;
|
||||
const preserveIDs = new Set(
|
||||
Array.isArray(preserve) ? preserve : preserve ? [preserve] : []
|
||||
);
|
||||
const preserveIDPrefixes = Array.isArray(preservePrefixes)
|
||||
? preservePrefixes
|
||||
: preservePrefixes
|
||||
? [preservePrefixes]
|
||||
: [];
|
||||
/**
|
||||
* @type {Map<string, XastElement>}
|
||||
*/
|
||||
const nodeById = new Map();
|
||||
/**
|
||||
* @type {Map<string, Array<{element: XastElement, name: string, value: string }>>}
|
||||
*/
|
||||
const referencesById = new Map();
|
||||
let deoptimized = false;
|
||||
|
||||
arr.forEach(function(i) {
|
||||
str += generateIDchars[i];
|
||||
});
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (force == false) {
|
||||
// deoptimize if style or script elements are present
|
||||
if (
|
||||
(node.name === 'style' || node.name === 'script') &&
|
||||
node.children.length !== 0
|
||||
) {
|
||||
deoptimized = true;
|
||||
return;
|
||||
}
|
||||
|
||||
return str;
|
||||
// avoid removing IDs if the whole SVG consists only of defs
|
||||
if (node.name === 'svg') {
|
||||
let hasDefsOnly = true;
|
||||
for (const child of node.children) {
|
||||
if (child.type !== 'element' || child.name !== 'defs') {
|
||||
hasDefsOnly = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasDefsOnly) {
|
||||
return visitSkip;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (name === 'id') {
|
||||
// collect all ids
|
||||
const id = value;
|
||||
if (nodeById.has(id)) {
|
||||
delete node.attributes.id; // remove repeated id
|
||||
} else {
|
||||
nodeById.set(id, node);
|
||||
}
|
||||
} else {
|
||||
// collect all references
|
||||
/**
|
||||
* @type {null | string}
|
||||
*/
|
||||
let id = null;
|
||||
if (referencesProps.includes(name)) {
|
||||
const match = value.match(regReferencesUrl);
|
||||
if (match != null) {
|
||||
id = match[2]; // url() reference
|
||||
}
|
||||
}
|
||||
if (name === 'href' || name.endsWith(':href')) {
|
||||
const match = value.match(regReferencesHref);
|
||||
if (match != null) {
|
||||
id = match[1]; // href reference
|
||||
}
|
||||
}
|
||||
if (name === 'begin') {
|
||||
const match = value.match(regReferencesBegin);
|
||||
if (match != null) {
|
||||
id = match[1]; // href reference
|
||||
}
|
||||
}
|
||||
if (id != null) {
|
||||
let refs = referencesById.get(id);
|
||||
if (refs == null) {
|
||||
refs = [];
|
||||
referencesById.set(id, refs);
|
||||
}
|
||||
refs.push({ element: node, name, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
root: {
|
||||
exit: () => {
|
||||
if (deoptimized) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* @type {(id: string) => boolean}
|
||||
**/
|
||||
const isIdPreserved = (id) =>
|
||||
preserveIDs.has(id) || hasStringPrefix(id, preserveIDPrefixes);
|
||||
/**
|
||||
* @type {null | Array<number>}
|
||||
*/
|
||||
let currentID = null;
|
||||
for (const [id, refs] of referencesById) {
|
||||
const node = nodeById.get(id);
|
||||
if (node != null) {
|
||||
// replace referenced IDs with the minified ones
|
||||
if (minify && isIdPreserved(id) === false) {
|
||||
/**
|
||||
* @type {null | string}
|
||||
*/
|
||||
let currentIDString = null;
|
||||
do {
|
||||
currentID = generateID(currentID);
|
||||
currentIDString = getIDstring(currentID, prefix);
|
||||
} while (isIdPreserved(currentIDString));
|
||||
node.attributes.id = currentIDString;
|
||||
for (const { element, name, value } of refs) {
|
||||
if (value.includes('#')) {
|
||||
// replace id in href and url()
|
||||
element.attributes[name] = value.replace(
|
||||
`#${id}`,
|
||||
`#${currentIDString}`
|
||||
);
|
||||
} else {
|
||||
// replace id in begin attribute
|
||||
element.attributes[name] = value.replace(
|
||||
`${id}.`,
|
||||
`${currentIDString}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// keep referenced node
|
||||
nodeById.delete(id);
|
||||
}
|
||||
}
|
||||
// remove non-referenced IDs attributes from elements
|
||||
if (remove) {
|
||||
for (const [id, node] of nodeById) {
|
||||
if (isIdPreserved(id) === false) {
|
||||
delete node.attributes.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
225
node_modules/svgo/plugins/cleanupListOfValues.js
generated
vendored
225
node_modules/svgo/plugins/cleanupListOfValues.js
generated
vendored
@@ -1,29 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { removeLeadingZero } = require('../lib/svgo/tools.js');
|
||||
|
||||
exports.name = 'cleanupListOfValues';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'rounds list of values to the fixed precision';
|
||||
|
||||
exports.params = {
|
||||
floatPrecision: 3,
|
||||
leadingZero: true,
|
||||
defaultPx: true,
|
||||
convertToPx: true
|
||||
const regNumericValues =
|
||||
/^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;
|
||||
const regSeparator = /\s+,?\s*|,\s*/;
|
||||
const absoluteLengths = {
|
||||
// relative to px
|
||||
cm: 96 / 2.54,
|
||||
mm: 96 / 25.4,
|
||||
in: 96,
|
||||
pt: 4 / 3,
|
||||
pc: 16,
|
||||
px: 1,
|
||||
};
|
||||
|
||||
var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
|
||||
regSeparator = /\s+,?\s*|,\s*/,
|
||||
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
|
||||
absoluteLengths = { // relative to px
|
||||
cm: 96/2.54,
|
||||
mm: 96/25.4,
|
||||
in: 96,
|
||||
pt: 4/3,
|
||||
pc: 16
|
||||
};
|
||||
|
||||
/**
|
||||
* Round list of values to the fixed precision.
|
||||
*
|
||||
@@ -32,110 +28,127 @@ var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|f
|
||||
* ⬇
|
||||
* <svg viewBox="0 0 200.284 200.284" enable-background="new 0 0 200.284 200.284">
|
||||
*
|
||||
*
|
||||
* <polygon points="208.250977 77.1308594 223.069336 ... "/>
|
||||
* ⬇
|
||||
* <polygon points="208.251 77.131 223.069 ... "/>
|
||||
*
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author kiyopikko
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* floatPrecision?: number,
|
||||
* leadingZero?: boolean,
|
||||
* defaultPx?: boolean,
|
||||
* convertToPx?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (_root, params) => {
|
||||
const {
|
||||
floatPrecision = 3,
|
||||
leadingZero = true,
|
||||
defaultPx = true,
|
||||
convertToPx = true,
|
||||
} = params;
|
||||
|
||||
/**
|
||||
* @type {(lists: string) => string}
|
||||
*/
|
||||
const roundValues = (lists) => {
|
||||
const roundedList = [];
|
||||
|
||||
if ( item.hasAttr('points') ) {
|
||||
roundValues(item.attrs.points);
|
||||
for (const elem of lists.split(regSeparator)) {
|
||||
const match = elem.match(regNumericValues);
|
||||
const matchNew = elem.match(/new/);
|
||||
|
||||
// if attribute value matches regNumericValues
|
||||
if (match) {
|
||||
// round it to the fixed precision
|
||||
let num = Number(Number(match[1]).toFixed(floatPrecision));
|
||||
/**
|
||||
* @type {any}
|
||||
*/
|
||||
let matchedUnit = match[3] || '';
|
||||
/**
|
||||
* @type{'' | keyof typeof absoluteLengths}
|
||||
*/
|
||||
let units = matchedUnit;
|
||||
|
||||
// convert absolute values to pixels
|
||||
if (convertToPx && units && units in absoluteLengths) {
|
||||
const pxNum = Number(
|
||||
(absoluteLengths[units] * Number(match[1])).toFixed(floatPrecision)
|
||||
);
|
||||
|
||||
if (pxNum.toString().length < match[0].length) {
|
||||
num = pxNum;
|
||||
units = 'px';
|
||||
}
|
||||
}
|
||||
|
||||
// and remove leading zero
|
||||
let str;
|
||||
if (leadingZero) {
|
||||
str = removeLeadingZero(num);
|
||||
} else {
|
||||
str = num.toString();
|
||||
}
|
||||
|
||||
// remove default 'px' units
|
||||
if (defaultPx && units === 'px') {
|
||||
units = '';
|
||||
}
|
||||
|
||||
roundedList.push(str + units);
|
||||
}
|
||||
// if attribute value is "new"(only enable-background).
|
||||
else if (matchNew) {
|
||||
roundedList.push('new');
|
||||
} else if (elem) {
|
||||
roundedList.push(elem);
|
||||
}
|
||||
}
|
||||
|
||||
if ( item.hasAttr('enable-background') ) {
|
||||
roundValues(item.attrs['enable-background']);
|
||||
}
|
||||
return roundedList.join(' ');
|
||||
};
|
||||
|
||||
if ( item.hasAttr('viewBox') ) {
|
||||
roundValues(item.attrs.viewBox);
|
||||
}
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.attributes.points != null) {
|
||||
node.attributes.points = roundValues(node.attributes.points);
|
||||
}
|
||||
|
||||
if ( item.hasAttr('stroke-dasharray') ) {
|
||||
roundValues(item.attrs['stroke-dasharray']);
|
||||
}
|
||||
if (node.attributes['enable-background'] != null) {
|
||||
node.attributes['enable-background'] = roundValues(
|
||||
node.attributes['enable-background']
|
||||
);
|
||||
}
|
||||
|
||||
if ( item.hasAttr('dx') ) {
|
||||
roundValues(item.attrs.dx);
|
||||
}
|
||||
if (node.attributes.viewBox != null) {
|
||||
node.attributes.viewBox = roundValues(node.attributes.viewBox);
|
||||
}
|
||||
|
||||
if ( item.hasAttr('dy') ) {
|
||||
roundValues(item.attrs.dy);
|
||||
}
|
||||
if (node.attributes['stroke-dasharray'] != null) {
|
||||
node.attributes['stroke-dasharray'] = roundValues(
|
||||
node.attributes['stroke-dasharray']
|
||||
);
|
||||
}
|
||||
|
||||
if ( item.hasAttr('x') ) {
|
||||
roundValues(item.attrs.x);
|
||||
}
|
||||
if (node.attributes.dx != null) {
|
||||
node.attributes.dx = roundValues(node.attributes.dx);
|
||||
}
|
||||
|
||||
if ( item.hasAttr('y') ) {
|
||||
roundValues(item.attrs.y);
|
||||
}
|
||||
if (node.attributes.dy != null) {
|
||||
node.attributes.dy = roundValues(node.attributes.dy);
|
||||
}
|
||||
|
||||
if (node.attributes.x != null) {
|
||||
node.attributes.x = roundValues(node.attributes.x);
|
||||
}
|
||||
|
||||
function roundValues($prop){
|
||||
|
||||
var num, units,
|
||||
match,
|
||||
matchNew,
|
||||
lists = $prop.value,
|
||||
listsArr = lists.split(regSeparator),
|
||||
roundedListArr = [],
|
||||
roundedList;
|
||||
|
||||
listsArr.forEach(function(elem){
|
||||
|
||||
match = elem.match(regNumericValues);
|
||||
matchNew = elem.match(/new/);
|
||||
|
||||
// if attribute value matches regNumericValues
|
||||
if(match){
|
||||
|
||||
// round it to the fixed precision
|
||||
num = +(+match[1]).toFixed(params.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);
|
||||
|
||||
if (String(pxNum).length < match[0].length)
|
||||
num = pxNum,
|
||||
units = 'px';
|
||||
}
|
||||
|
||||
// and remove leading zero
|
||||
if (params.leadingZero) {
|
||||
num = removeLeadingZero(num);
|
||||
}
|
||||
|
||||
// remove default 'px' units
|
||||
if (params.defaultPx && units === 'px') {
|
||||
units = '';
|
||||
}
|
||||
|
||||
roundedListArr.push(num+units);
|
||||
|
||||
}
|
||||
// if attribute value is "new"(only enable-background).
|
||||
else if(matchNew){
|
||||
|
||||
roundedListArr.push('new');
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
roundedList = roundedListArr.join(' ');
|
||||
$prop.value = roundedList;
|
||||
|
||||
}
|
||||
|
||||
if (node.attributes.y != null) {
|
||||
node.attributes.y = roundValues(node.attributes.y);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
143
node_modules/svgo/plugins/cleanupNumericValues.js
generated
vendored
143
node_modules/svgo/plugins/cleanupNumericValues.js
generated
vendored
@@ -1,76 +1,113 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { removeLeadingZero } = require('../lib/svgo/tools');
|
||||
|
||||
exports.name = 'cleanupNumericValues';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
exports.description =
|
||||
'rounds numeric values to the fixed precision, removes default ‘px’ units';
|
||||
|
||||
exports.description = 'rounds numeric values to the fixed precision, removes default ‘px’ units';
|
||||
const regNumericValues =
|
||||
/^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;
|
||||
|
||||
exports.params = {
|
||||
floatPrecision: 3,
|
||||
leadingZero: true,
|
||||
defaultPx: true,
|
||||
convertToPx: true
|
||||
const absoluteLengths = {
|
||||
// relative to px
|
||||
cm: 96 / 2.54,
|
||||
mm: 96 / 25.4,
|
||||
in: 96,
|
||||
pt: 4 / 3,
|
||||
pc: 16,
|
||||
px: 1,
|
||||
};
|
||||
|
||||
var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
|
||||
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
|
||||
absoluteLengths = { // relative to px
|
||||
cm: 96/2.54,
|
||||
mm: 96/25.4,
|
||||
in: 96,
|
||||
pt: 4/3,
|
||||
pc: 16
|
||||
};
|
||||
|
||||
/**
|
||||
* Round numeric values to the fixed precision,
|
||||
* remove default 'px' units.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* floatPrecision?: number,
|
||||
* leadingZero?: boolean,
|
||||
* defaultPx?: boolean,
|
||||
* convertToPx?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (_root, params) => {
|
||||
const {
|
||||
floatPrecision = 3,
|
||||
leadingZero = true,
|
||||
defaultPx = true,
|
||||
convertToPx = true,
|
||||
} = params;
|
||||
|
||||
if (item.isElem()) {
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.attributes.viewBox != null) {
|
||||
const nums = node.attributes.viewBox.split(/\s,?\s*|,\s*/g);
|
||||
node.attributes.viewBox = nums
|
||||
.map((value) => {
|
||||
const num = Number(value);
|
||||
return Number.isNaN(num)
|
||||
? value
|
||||
: Number(num.toFixed(floatPrecision));
|
||||
})
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
var match;
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
// The `version` attribute is a text string and cannot be rounded
|
||||
if (name === 'version') {
|
||||
continue;
|
||||
}
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
match = attr.value.match(regNumericValues);
|
||||
const match = value.match(regNumericValues);
|
||||
|
||||
// if attribute value matches regNumericValues
|
||||
if (match) {
|
||||
// round it to the fixed precision
|
||||
var num = +(+match[1]).toFixed(params.floatPrecision),
|
||||
units = match[3] || '';
|
||||
// if attribute value matches regNumericValues
|
||||
if (match) {
|
||||
// round it to the fixed precision
|
||||
let num = Number(Number(match[1]).toFixed(floatPrecision));
|
||||
/**
|
||||
* @type {any}
|
||||
*/
|
||||
let matchedUnit = match[3] || '';
|
||||
/**
|
||||
* @type{'' | keyof typeof absoluteLengths}
|
||||
*/
|
||||
let units = matchedUnit;
|
||||
|
||||
// convert absolute values to pixels
|
||||
if (params.convertToPx && units && (units in absoluteLengths)) {
|
||||
var pxNum = +(absoluteLengths[units] * match[1]).toFixed(params.floatPrecision);
|
||||
|
||||
if (String(pxNum).length < match[0].length)
|
||||
num = pxNum,
|
||||
units = 'px';
|
||||
}
|
||||
|
||||
// and remove leading zero
|
||||
if (params.leadingZero) {
|
||||
num = removeLeadingZero(num);
|
||||
}
|
||||
|
||||
// remove default 'px' units
|
||||
if (params.defaultPx && units === 'px') {
|
||||
units = '';
|
||||
}
|
||||
|
||||
attr.value = num + units;
|
||||
// convert absolute values to pixels
|
||||
if (convertToPx && units !== '' && units in absoluteLengths) {
|
||||
const pxNum = Number(
|
||||
(absoluteLengths[units] * Number(match[1])).toFixed(
|
||||
floatPrecision
|
||||
)
|
||||
);
|
||||
if (pxNum.toString().length < match[0].length) {
|
||||
num = pxNum;
|
||||
units = 'px';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
// and remove leading zero
|
||||
let str;
|
||||
if (leadingZero) {
|
||||
str = removeLeadingZero(num);
|
||||
} else {
|
||||
str = num.toString();
|
||||
}
|
||||
|
||||
// remove default 'px' units
|
||||
if (defaultPx && units === 'px') {
|
||||
units = '';
|
||||
}
|
||||
|
||||
node.attributes[name] = str + units;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
155
node_modules/svgo/plugins/collapseGroups.js
generated
vendored
155
node_modules/svgo/plugins/collapseGroups.js
generated
vendored
@@ -1,19 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItemReverse';
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastNode} XastNode
|
||||
*/
|
||||
|
||||
const { inheritableAttrs, elemsGroups } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'collapseGroups';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'collapses useless groups';
|
||||
|
||||
var animationElems = require('./_collections').elemsGroups.animation;
|
||||
/**
|
||||
* @type {(node: XastNode, name: string) => boolean}
|
||||
*/
|
||||
const hasAnimatedAttr = (node, name) => {
|
||||
if (node.type === 'element') {
|
||||
if (
|
||||
elemsGroups.animation.includes(node.name) &&
|
||||
node.attributes.attributeName === name
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
for (const child of node.children) {
|
||||
if (hasAnimatedAttr(child, name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
function hasAnimatedAttr(item) {
|
||||
return item.isElem(animationElems) && item.hasAttr('attributeName', this) ||
|
||||
!item.isEmpty() && item.content.some(hasAnimatedAttr, this);
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Collapse useless groups.
|
||||
*
|
||||
* @example
|
||||
@@ -31,50 +49,87 @@ function hasAnimatedAttr(item) {
|
||||
* ⬇
|
||||
* <path attr1="val1" d="..."/>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
exit: (node, parentNode) => {
|
||||
if (parentNode.type === 'root' || parentNode.name === 'switch') {
|
||||
return;
|
||||
}
|
||||
// non-empty groups
|
||||
if (node.name !== 'g' || node.children.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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') && (
|
||||
!g.hasAttr('clip-path') ||
|
||||
inner.isElem('g') && !g.hasAttr('transform') && !inner.hasAttr('transform')
|
||||
)) {
|
||||
g.eachAttr(function(attr) {
|
||||
if (g.content.some(hasAnimatedAttr, attr.name)) return;
|
||||
|
||||
if (!inner.hasAttr(attr.name)) {
|
||||
inner.addAttr(attr);
|
||||
} else if (attr.name == 'transform' || attr.name == 'class') {
|
||||
inner.attr(attr.name).value = attr.value + ' ' + inner.attr(attr.name).value;
|
||||
}
|
||||
g.removeAttr(attr.name);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// collapse groups without attributes
|
||||
if (!g.hasAttr() && !g.content.some(function(item) { return item.isElem(animationElems) })) {
|
||||
item.spliceContent(i, 1, g.content);
|
||||
}
|
||||
// move group attibutes to the single child element
|
||||
if (
|
||||
Object.keys(node.attributes).length !== 0 &&
|
||||
node.children.length === 1
|
||||
) {
|
||||
const firstChild = node.children[0];
|
||||
// TODO untangle this mess
|
||||
if (
|
||||
firstChild.type === 'element' &&
|
||||
firstChild.attributes.id == null &&
|
||||
node.attributes.filter == null &&
|
||||
(node.attributes.class == null ||
|
||||
firstChild.attributes.class == null) &&
|
||||
((node.attributes['clip-path'] == null &&
|
||||
node.attributes.mask == null) ||
|
||||
(firstChild.name === 'g' &&
|
||||
node.attributes.transform == null &&
|
||||
firstChild.attributes.transform == null))
|
||||
) {
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
// avoid copying to not conflict with animated attribute
|
||||
if (hasAnimatedAttr(firstChild, name)) {
|
||||
return;
|
||||
}
|
||||
if (firstChild.attributes[name] == null) {
|
||||
firstChild.attributes[name] = value;
|
||||
} else if (name === 'transform') {
|
||||
firstChild.attributes[name] =
|
||||
value + ' ' + firstChild.attributes[name];
|
||||
} else if (firstChild.attributes[name] === 'inherit') {
|
||||
firstChild.attributes[name] = value;
|
||||
} else if (
|
||||
inheritableAttrs.includes(name) === false &&
|
||||
firstChild.attributes[name] !== value
|
||||
) {
|
||||
return;
|
||||
}
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// collapse groups without attributes
|
||||
if (Object.keys(node.attributes).length === 0) {
|
||||
// animation elements "add" attributes to group
|
||||
// group should be preserved
|
||||
for (const child of node.children) {
|
||||
if (
|
||||
child.type === 'element' &&
|
||||
elemsGroups.animation.includes(child.name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// replace current node with all its children
|
||||
const index = parentNode.children.indexOf(node);
|
||||
parentNode.children.splice(index, 1, ...node.children);
|
||||
// TODO remove in v3
|
||||
for (const child of node.children) {
|
||||
// @ts-ignore parentNode is forbidden for public usage
|
||||
// and will be moved in v3
|
||||
child.parentNode = parentNode;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
200
node_modules/svgo/plugins/convertColors.js
generated
vendored
200
node_modules/svgo/plugins/convertColors.js
generated
vendored
@@ -1,31 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const collections = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'convertColors';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'converts colors: rgb() to #rrggbb and #rrggbb to #rgb';
|
||||
|
||||
exports.params = {
|
||||
currentColor: false,
|
||||
names2hex: true,
|
||||
rgb2hex: true,
|
||||
shorthex: true,
|
||||
shortname: true
|
||||
};
|
||||
const rNumber = '([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)';
|
||||
const rComma = '\\s*,\\s*';
|
||||
const regRGB = new RegExp(
|
||||
'^rgb\\(\\s*' + rNumber + rComma + rNumber + rComma + rNumber + '\\s*\\)$'
|
||||
);
|
||||
const regHEX = /^#(([a-fA-F0-9])\2){3}$/;
|
||||
|
||||
var collections = require('./_collections'),
|
||||
rNumber = '([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)',
|
||||
rComma = '\\s*,\\s*',
|
||||
regRGB = new RegExp('^rgb\\(\\s*' + rNumber + rComma + rNumber + rComma + rNumber + '\\s*\\)$'),
|
||||
regHEX = /^\#(([a-fA-F0-9])\2){3}$/,
|
||||
none = /\bnone\b/i;
|
||||
/**
|
||||
* Convert [r, g, b] to #rrggbb.
|
||||
*
|
||||
* @see https://gist.github.com/983535
|
||||
*
|
||||
* @example
|
||||
* rgb2hex([255, 255, 255]) // '#ffffff'
|
||||
*
|
||||
* @author Jed Schmidt
|
||||
*
|
||||
* @type {(rgb: Array<number>) => string}
|
||||
*/
|
||||
const convertRgbToHex = ([r, g, b]) => {
|
||||
// combine the octets into a 32-bit integer as: [1][r][g][b]
|
||||
const hexNumber =
|
||||
// operator precedence is (+) > (<<) > (|)
|
||||
((((256 + // [1][0]
|
||||
r) << // [1][r]
|
||||
8) | // [1][r][0]
|
||||
g) << // [1][r][g]
|
||||
8) | // [1][r][g][0]
|
||||
b;
|
||||
// serialize [1][r][g][b] to a hex string, and
|
||||
// remove the 1 to get the number with 0s intact
|
||||
return '#' + hexNumber.toString(16).slice(1).toUpperCase();
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert different colors formats in element attributes to hex.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/types.html#DataTypeColor
|
||||
* @see http://www.w3.org/TR/SVG/single-page.html#types-ColorKeywords
|
||||
* @see https://www.w3.org/TR/SVG11/types.html#DataTypeColor
|
||||
* @see https://www.w3.org/TR/SVG11/single-page.html#types-ColorKeywords
|
||||
*
|
||||
* @example
|
||||
* Convert color name keyword to long hex:
|
||||
@@ -41,78 +61,92 @@ var collections = require('./_collections'),
|
||||
* Convert hex to short name
|
||||
* #000080 ➡ navy
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* currentColor?: boolean | string | RegExp,
|
||||
* names2hex?: boolean,
|
||||
* rgb2hex?: boolean,
|
||||
* shorthex?: boolean,
|
||||
* shortname?: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (_root, params) => {
|
||||
const {
|
||||
currentColor = false,
|
||||
names2hex = true,
|
||||
rgb2hex = true,
|
||||
shorthex = true,
|
||||
shortname = true,
|
||||
} = params;
|
||||
|
||||
if (item.elem) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
|
||||
if (collections.colorsProps.indexOf(attr.name) > -1) {
|
||||
|
||||
var val = attr.value,
|
||||
match;
|
||||
|
||||
// Convert colors to currentColor
|
||||
if (params.currentColor && (match = !val.match(none))) {
|
||||
val = 'currentColor';
|
||||
}
|
||||
|
||||
// Convert color name keyword to long hex
|
||||
if (params.names2hex && val.toLowerCase() in collections.colorsNames) {
|
||||
val = collections.colorsNames[val.toLowerCase()];
|
||||
}
|
||||
|
||||
// Convert rgb() to long hex
|
||||
if (params.rgb2hex && (match = val.match(regRGB))) {
|
||||
match = match.slice(1, 4).map(function(m) {
|
||||
if (m.indexOf('%') > -1)
|
||||
m = Math.round(parseFloat(m) * 2.55);
|
||||
|
||||
return Math.max(0, Math.min(m, 255));
|
||||
});
|
||||
|
||||
val = rgb2hex(match);
|
||||
}
|
||||
|
||||
// Convert long hex to short hex
|
||||
if (params.shorthex && (match = val.match(regHEX))) {
|
||||
val = '#' + match[0][1] + match[0][3] + match[0][5];
|
||||
}
|
||||
|
||||
// Convert hex to short name
|
||||
if (params.shortname && val in collections.colorsShortNames) {
|
||||
val = collections.colorsShortNames[val];
|
||||
}
|
||||
|
||||
attr.value = val;
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (collections.colorsProps.includes(name)) {
|
||||
let val = value;
|
||||
|
||||
// convert colors to currentColor
|
||||
if (currentColor) {
|
||||
let matched;
|
||||
if (typeof currentColor === 'string') {
|
||||
matched = val === currentColor;
|
||||
} else if (currentColor instanceof RegExp) {
|
||||
matched = currentColor.exec(val) != null;
|
||||
} else {
|
||||
matched = val !== 'none';
|
||||
}
|
||||
if (matched) {
|
||||
val = 'currentColor';
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
// convert color name keyword to long hex
|
||||
if (names2hex) {
|
||||
const colorName = val.toLowerCase();
|
||||
if (collections.colorsNames[colorName] != null) {
|
||||
val = collections.colorsNames[colorName];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// convert rgb() to long hex
|
||||
if (rgb2hex) {
|
||||
let match = val.match(regRGB);
|
||||
if (match != null) {
|
||||
let nums = match.slice(1, 4).map((m) => {
|
||||
let n;
|
||||
if (m.indexOf('%') > -1) {
|
||||
n = Math.round(parseFloat(m) * 2.55);
|
||||
} else {
|
||||
n = Number(m);
|
||||
}
|
||||
return Math.max(0, Math.min(n, 255));
|
||||
});
|
||||
val = convertRgbToHex(nums);
|
||||
}
|
||||
}
|
||||
|
||||
// convert long hex to short hex
|
||||
if (shorthex) {
|
||||
let match = val.match(regHEX);
|
||||
if (match != null) {
|
||||
val = '#' + match[0][1] + match[0][3] + match[0][5];
|
||||
}
|
||||
}
|
||||
|
||||
// convert hex to short name
|
||||
if (shortname) {
|
||||
const colorName = val.toLowerCase();
|
||||
if (collections.colorsShortNames[colorName] != null) {
|
||||
val = collections.colorsShortNames[colorName];
|
||||
}
|
||||
}
|
||||
|
||||
node.attributes[name] = val;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert [r, g, b] to #rrggbb.
|
||||
*
|
||||
* @see https://gist.github.com/983535
|
||||
*
|
||||
* @example
|
||||
* rgb2hex([255, 255, 255]) // '#ffffff'
|
||||
*
|
||||
* @param {Array} rgb [r, g, b]
|
||||
* @return {String} #rrggbb
|
||||
*
|
||||
* @author Jed Schmidt
|
||||
*/
|
||||
function rgb2hex(rgb) {
|
||||
return '#' + ('00000' + (rgb[0] << 16 | rgb[1] << 8 | rgb[2]).toString(16)).slice(-6).toUpperCase();
|
||||
}
|
||||
|
||||
39
node_modules/svgo/plugins/convertEllipseToCircle.js
generated
vendored
Normal file
39
node_modules/svgo/plugins/convertEllipseToCircle.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
exports.name = 'convertEllipseToCircle';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
exports.description = 'converts non-eccentric <ellipse>s to <circle>s';
|
||||
|
||||
/**
|
||||
* Converts non-eccentric <ellipse>s to <circle>s.
|
||||
*
|
||||
* @see https://www.w3.org/TR/SVG11/shapes.html
|
||||
*
|
||||
* @author Taylor Hunt
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.name === 'ellipse') {
|
||||
const rx = node.attributes.rx || '0';
|
||||
const ry = node.attributes.ry || '0';
|
||||
if (
|
||||
rx === ry ||
|
||||
rx === 'auto' ||
|
||||
ry === 'auto' // SVG2
|
||||
) {
|
||||
node.name = 'circle';
|
||||
const radius = rx === 'auto' ? ry : rx;
|
||||
delete node.attributes.rx;
|
||||
delete node.attributes.ry;
|
||||
node.attributes.r = radius;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
1494
node_modules/svgo/plugins/convertPathData.js
generated
vendored
1494
node_modules/svgo/plugins/convertPathData.js
generated
vendored
File diff suppressed because it is too large
Load Diff
234
node_modules/svgo/plugins/convertShapeToPath.js
generated
vendored
234
node_modules/svgo/plugins/convertShapeToPath.js
generated
vendored
@@ -1,103 +1,175 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
/**
|
||||
* @typedef {import('../lib/types').PathDataItem} PathDataItem
|
||||
*/
|
||||
|
||||
const { stringifyPathData } = require('../lib/path.js');
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'convertShapeToPath';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'converts basic shapes to more compact path form';
|
||||
|
||||
var none = { value: 0 },
|
||||
regNumber = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
|
||||
const regNumber = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
|
||||
|
||||
/**
|
||||
* Converts basic shape to more compact path.
|
||||
* It also allows further optimizations like
|
||||
* combining paths with similar attributes.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/shapes.html
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
* @see https://www.w3.org/TR/SVG11/shapes.html
|
||||
*
|
||||
* @author Lev Solntsev
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* convertArcs?: boolean,
|
||||
* floatPrecision?: number
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
exports.fn = (root, params) => {
|
||||
const { convertArcs = false, floatPrecision: precision } = params;
|
||||
|
||||
if (
|
||||
item.isElem('rect') &&
|
||||
item.hasAttr('width') &&
|
||||
item.hasAttr('height') &&
|
||||
!item.hasAttr('rx') &&
|
||||
!item.hasAttr('ry')
|
||||
) {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// convert rect to path
|
||||
if (
|
||||
node.name === 'rect' &&
|
||||
node.attributes.width != null &&
|
||||
node.attributes.height != null &&
|
||||
node.attributes.rx == null &&
|
||||
node.attributes.ry == null
|
||||
) {
|
||||
const x = Number(node.attributes.x || '0');
|
||||
const y = Number(node.attributes.y || '0');
|
||||
const width = Number(node.attributes.width);
|
||||
const height = Number(node.attributes.height);
|
||||
// Values like '100%' compute to NaN, thus running after
|
||||
// cleanupNumericValues when 'px' units has already been removed.
|
||||
// TODO: Calculate sizes from % and non-px units if possible.
|
||||
if (Number.isNaN(x - y + width - height)) return;
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [
|
||||
{ command: 'M', args: [x, y] },
|
||||
{ command: 'H', args: [x + width] },
|
||||
{ command: 'V', args: [y + height] },
|
||||
{ command: 'H', args: [x] },
|
||||
{ command: 'z', args: [] },
|
||||
];
|
||||
node.name = 'path';
|
||||
node.attributes.d = stringifyPathData({ pathData, precision });
|
||||
delete node.attributes.x;
|
||||
delete node.attributes.y;
|
||||
delete node.attributes.width;
|
||||
delete node.attributes.height;
|
||||
}
|
||||
|
||||
var x = +(item.attr('x') || none).value,
|
||||
y = +(item.attr('y') || none).value,
|
||||
width = +item.attr('width').value,
|
||||
height = +item.attr('height').value;
|
||||
// convert line to path
|
||||
if (node.name === 'line') {
|
||||
const x1 = Number(node.attributes.x1 || '0');
|
||||
const y1 = Number(node.attributes.y1 || '0');
|
||||
const x2 = Number(node.attributes.x2 || '0');
|
||||
const y2 = Number(node.attributes.y2 || '0');
|
||||
if (Number.isNaN(x1 - y1 + x2 - y2)) return;
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [
|
||||
{ command: 'M', args: [x1, y1] },
|
||||
{ command: 'L', args: [x2, y2] },
|
||||
];
|
||||
node.name = 'path';
|
||||
node.attributes.d = stringifyPathData({ pathData, precision });
|
||||
delete node.attributes.x1;
|
||||
delete node.attributes.y1;
|
||||
delete node.attributes.x2;
|
||||
delete node.attributes.y2;
|
||||
}
|
||||
|
||||
// Values like '100%' compute to NaN, thus running after
|
||||
// cleanupNumericValues when 'px' units has already been removed.
|
||||
// TODO: Calculate sizes from % and non-px units if possible.
|
||||
if (isNaN(x - y + width - height)) return;
|
||||
|
||||
var pathData =
|
||||
'M' + x + ' ' + y +
|
||||
'H' + (x + width) +
|
||||
'V' + (y + height) +
|
||||
'H' + x +
|
||||
'z';
|
||||
|
||||
item.addAttr({
|
||||
name: 'd',
|
||||
value: pathData,
|
||||
prefix: '',
|
||||
local: 'd'
|
||||
// convert polyline and polygon to path
|
||||
if (
|
||||
(node.name === 'polyline' || node.name === 'polygon') &&
|
||||
node.attributes.points != null
|
||||
) {
|
||||
const coords = (node.attributes.points.match(regNumber) || []).map(
|
||||
Number
|
||||
);
|
||||
if (coords.length < 4) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [];
|
||||
for (let i = 0; i < coords.length; i += 2) {
|
||||
pathData.push({
|
||||
command: i === 0 ? 'M' : 'L',
|
||||
args: coords.slice(i, i + 2),
|
||||
});
|
||||
}
|
||||
if (node.name === 'polygon') {
|
||||
pathData.push({ command: 'z', args: [] });
|
||||
}
|
||||
node.name = 'path';
|
||||
node.attributes.d = stringifyPathData({ pathData, precision });
|
||||
delete node.attributes.points;
|
||||
}
|
||||
|
||||
item.renameElem('path')
|
||||
.removeAttr(['x', 'y', 'width', 'height']);
|
||||
|
||||
} else if (item.isElem('line')) {
|
||||
|
||||
var x1 = +(item.attr('x1') || none).value,
|
||||
y1 = +(item.attr('y1') || none).value,
|
||||
x2 = +(item.attr('x2') || none).value,
|
||||
y2 = +(item.attr('y2') || none).value;
|
||||
if (isNaN(x1 - y1 + x2 - y2)) return;
|
||||
|
||||
item.addAttr({
|
||||
name: 'd',
|
||||
value: 'M' + x1 + ' ' + y1 + 'L' + x2 + ' ' + y2,
|
||||
prefix: '',
|
||||
local: 'd'
|
||||
});
|
||||
|
||||
item.renameElem('path')
|
||||
.removeAttr(['x1', 'y1', 'x2', 'y2']);
|
||||
|
||||
} else if ((
|
||||
item.isElem('polyline') ||
|
||||
item.isElem('polygon')
|
||||
) &&
|
||||
item.hasAttr('points')
|
||||
) {
|
||||
|
||||
var coords = (item.attr('points').value.match(regNumber) || []).map(Number);
|
||||
if (coords.length < 4) return false;
|
||||
|
||||
item.addAttr({
|
||||
name: 'd',
|
||||
value: 'M' + coords.slice(0,2).join(' ') +
|
||||
'L' + coords.slice(2).join(' ') +
|
||||
(item.isElem('polygon') ? 'z' : ''),
|
||||
prefix: '',
|
||||
local: 'd'
|
||||
});
|
||||
|
||||
item.renameElem('path')
|
||||
.removeAttr('points');
|
||||
}
|
||||
// optionally convert circle
|
||||
if (node.name === 'circle' && convertArcs) {
|
||||
const cx = Number(node.attributes.cx || '0');
|
||||
const cy = Number(node.attributes.cy || '0');
|
||||
const r = Number(node.attributes.r || '0');
|
||||
if (Number.isNaN(cx - cy + r)) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [
|
||||
{ command: 'M', args: [cx, cy - r] },
|
||||
{ command: 'A', args: [r, r, 0, 1, 0, cx, cy + r] },
|
||||
{ command: 'A', args: [r, r, 0, 1, 0, cx, cy - r] },
|
||||
{ command: 'z', args: [] },
|
||||
];
|
||||
node.name = 'path';
|
||||
node.attributes.d = stringifyPathData({ pathData, precision });
|
||||
delete node.attributes.cx;
|
||||
delete node.attributes.cy;
|
||||
delete node.attributes.r;
|
||||
}
|
||||
|
||||
// optionally covert ellipse
|
||||
if (node.name === 'ellipse' && convertArcs) {
|
||||
const ecx = Number(node.attributes.cx || '0');
|
||||
const ecy = Number(node.attributes.cy || '0');
|
||||
const rx = Number(node.attributes.rx || '0');
|
||||
const ry = Number(node.attributes.ry || '0');
|
||||
if (Number.isNaN(ecx - ecy + rx - ry)) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const pathData = [
|
||||
{ command: 'M', args: [ecx, ecy - ry] },
|
||||
{ command: 'A', args: [rx, ry, 0, 1, 0, ecx, ecy + ry] },
|
||||
{ command: 'A', args: [rx, ry, 0, 1, 0, ecx, ecy - ry] },
|
||||
{ command: 'z', args: [] },
|
||||
];
|
||||
node.name = 'path';
|
||||
node.attributes.d = stringifyPathData({ pathData, precision });
|
||||
delete node.attributes.cx;
|
||||
delete node.attributes.cy;
|
||||
delete node.attributes.rx;
|
||||
delete node.attributes.ry;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
179
node_modules/svgo/plugins/convertStyleToAttrs.js
generated
vendored
179
node_modules/svgo/plugins/convertStyleToAttrs.js
generated
vendored
@@ -1,35 +1,54 @@
|
||||
/* jshint quotmark: false */
|
||||
'use strict';
|
||||
|
||||
exports.name = 'convertStyleToAttrs';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.active = true;
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'converts style to attributes';
|
||||
|
||||
var EXTEND = require('whet.extend'),
|
||||
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'
|
||||
rQuotes = '"(?:[^"\\n\\r\\\\]|' + rEscape + ')*?(?:"|$)', // string in double quotes: "smth"
|
||||
rQuotedString = new RegExp('^' + g(rSingleQuotes, rQuotes) + '$'),
|
||||
exports.params = {
|
||||
keepImportant: false,
|
||||
};
|
||||
|
||||
// Parentheses, E.g.: url(data:image/png;base64,iVBO...).
|
||||
// ':' and ';' inside of it should be threated as is. (Just like in strings.)
|
||||
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, '[^;]*?') + '*?' + ')',
|
||||
|
||||
// End of declaration. Spaces outside of capturing groups help to do natural trimming.
|
||||
rDeclEnd = '\\s*(?:;\\s*|$)',
|
||||
|
||||
// Final RegExp to parse CSS declarations.
|
||||
regDeclarationBlock = new RegExp(rAttr + ':' + rValue + rDeclEnd, 'ig'),
|
||||
|
||||
// Comments expression. Honors escape sequences and strings.
|
||||
regStripComments = new RegExp(g(rEscape, rSingleQuotes, rQuotes, '/\\*[^]*?\\*/'), 'ig');
|
||||
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'
|
||||
rQuotes = '"(?:[^"\\n\\r\\\\]|' + rEscape + ')*?(?:"|$)', // string in double quotes: "smth"
|
||||
rQuotedString = new RegExp('^' + g(rSingleQuotes, rQuotes) + '$'),
|
||||
// Parentheses, E.g.: url(data:image/png;base64,iVBO...).
|
||||
// ':' and ';' inside of it should be threated as is. (Just like in strings.)
|
||||
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,
|
||||
'[^;]*?'
|
||||
) +
|
||||
'*?' +
|
||||
')',
|
||||
// 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 + rImportant + rDeclEnd,
|
||||
'ig'
|
||||
),
|
||||
// Comments expression. Honors escape sequences and strings.
|
||||
regStripComments = new RegExp(
|
||||
g(rEscape, rSingleQuotes, rQuotes, '/\\*[^]*?\\*/'),
|
||||
'ig'
|
||||
);
|
||||
|
||||
/**
|
||||
* Convert style in attributes. Cleanups comments and illegal declarations (without colon) as a side effect.
|
||||
@@ -49,69 +68,65 @@ var EXTEND = require('whet.extend'),
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
/* jshint boss: true */
|
||||
exports.fn = function (item, params) {
|
||||
if (item.type === 'element' && item.attributes.style != null) {
|
||||
// ['opacity: 1', 'color: #000']
|
||||
let styles = [];
|
||||
const newAttributes = {};
|
||||
|
||||
if (item.elem && item.hasAttr('style')) {
|
||||
// ['opacity: 1', 'color: #000']
|
||||
var styleValue = item.attr('style').value,
|
||||
styles = [],
|
||||
attrs = {};
|
||||
|
||||
// Strip CSS comments preserving escape sequences and strings.
|
||||
styleValue = styleValue.replace(regStripComments, function(match) {
|
||||
return match[0] == '/' ? '' :
|
||||
match[0] == '\\' && /[-g-z]/i.test(match[1]) ? match[1] : match;
|
||||
});
|
||||
|
||||
regDeclarationBlock.lastIndex = 0;
|
||||
for (var rule; rule = regDeclarationBlock.exec(styleValue);) {
|
||||
styles.push([rule[1], rule[2]]);
|
||||
}
|
||||
|
||||
if (styles.length) {
|
||||
|
||||
styles = styles.filter(function(style) {
|
||||
if (style[0]) {
|
||||
var prop = style[0].toLowerCase(),
|
||||
val = style[1];
|
||||
|
||||
if (rQuotedString.test(val)) {
|
||||
val = val.slice(1, -1);
|
||||
}
|
||||
|
||||
if (stylingProps.indexOf(prop) > -1) {
|
||||
|
||||
attrs[prop] = {
|
||||
name: prop,
|
||||
value: val,
|
||||
local: prop,
|
||||
prefix: ''
|
||||
};
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
EXTEND(item.attrs, attrs);
|
||||
|
||||
if (styles.length) {
|
||||
item.attr('style').value = styles
|
||||
.map(function(declaration) { return declaration.join(':') })
|
||||
.join(';');
|
||||
} else {
|
||||
item.removeAttr('style');
|
||||
}
|
||||
|
||||
}
|
||||
// Strip CSS comments preserving escape sequences and strings.
|
||||
const styleValue = item.attributes.style.replace(
|
||||
regStripComments,
|
||||
(match) => {
|
||||
return match[0] == '/'
|
||||
? ''
|
||||
: match[0] == '\\' && /[-g-z]/i.test(match[1])
|
||||
? match[1]
|
||||
: match;
|
||||
}
|
||||
);
|
||||
|
||||
regDeclarationBlock.lastIndex = 0;
|
||||
// eslint-disable-next-line no-cond-assign
|
||||
for (var rule; (rule = regDeclarationBlock.exec(styleValue)); ) {
|
||||
if (!params.keepImportant || !rule[3]) {
|
||||
styles.push([rule[1], rule[2]]);
|
||||
}
|
||||
}
|
||||
|
||||
if (styles.length) {
|
||||
styles = styles.filter(function (style) {
|
||||
if (style[0]) {
|
||||
var prop = style[0].toLowerCase(),
|
||||
val = style[1];
|
||||
|
||||
if (rQuotedString.test(val)) {
|
||||
val = val.slice(1, -1);
|
||||
}
|
||||
|
||||
if (stylingProps.includes(prop)) {
|
||||
newAttributes[prop] = val;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
Object.assign(item.attributes, newAttributes);
|
||||
|
||||
if (styles.length) {
|
||||
item.attributes.style = styles
|
||||
.map((declaration) => declaration.join(':'))
|
||||
.join(';');
|
||||
} else {
|
||||
delete item.attributes.style;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function g() {
|
||||
return '(?:' + Array.prototype.join.call(arguments, '|') + ')';
|
||||
return '(?:' + Array.prototype.join.call(arguments, '|') + ')';
|
||||
}
|
||||
|
||||
628
node_modules/svgo/plugins/convertTransform.js
generated
vendored
628
node_modules/svgo/plugins/convertTransform.js
generated
vendored
@@ -1,103 +1,146 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
*/
|
||||
|
||||
const { cleanupOutData } = require('../lib/svgo/tools.js');
|
||||
const {
|
||||
transform2js,
|
||||
transformsMultiply,
|
||||
matrixToTransform,
|
||||
} = require('./_transforms.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'convertTransform';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'collapses multiple transformations and optimizes it';
|
||||
|
||||
exports.params = {
|
||||
convertToShorts: true,
|
||||
// degPrecision: 3, // transformPrecision (or matrix precision) - 2 by default
|
||||
floatPrecision: 3,
|
||||
transformPrecision: 5,
|
||||
matrixToTransform: true,
|
||||
shortTranslate: true,
|
||||
shortScale: true,
|
||||
shortRotate: true,
|
||||
removeUseless: true,
|
||||
collapseIntoOne: true,
|
||||
leadingZero: true,
|
||||
negativeExtraSpace: false
|
||||
};
|
||||
|
||||
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,
|
||||
degRound,
|
||||
floatRound,
|
||||
transformRound;
|
||||
|
||||
/**
|
||||
* Convert matrices to the short aliases,
|
||||
* convert long translate, scale or rotate transform notations to the shorts ones,
|
||||
* convert transforms to the matrices and multiply them all into one,
|
||||
* remove useless transforms.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/coords.html#TransformMatrixDefined
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
* @see https://www.w3.org/TR/SVG11/coords.html#TransformMatrixDefined
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* convertToShorts?: boolean,
|
||||
* degPrecision?: number,
|
||||
* floatPrecision?: number,
|
||||
* transformPrecision?: number,
|
||||
* matrixToTransform?: boolean,
|
||||
* shortTranslate?: boolean,
|
||||
* shortScale?: boolean,
|
||||
* shortRotate?: boolean,
|
||||
* removeUseless?: boolean,
|
||||
* collapseIntoOne?: boolean,
|
||||
* leadingZero?: boolean,
|
||||
* negativeExtraSpace?: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
|
||||
if (item.elem) {
|
||||
|
||||
exports.fn = (_root, params) => {
|
||||
const {
|
||||
convertToShorts = true,
|
||||
// degPrecision = 3, // transformPrecision (or matrix precision) - 2 by default
|
||||
degPrecision,
|
||||
floatPrecision = 3,
|
||||
transformPrecision = 5,
|
||||
matrixToTransform = true,
|
||||
shortTranslate = true,
|
||||
shortScale = true,
|
||||
shortRotate = true,
|
||||
removeUseless = true,
|
||||
collapseIntoOne = true,
|
||||
leadingZero = true,
|
||||
negativeExtraSpace = false,
|
||||
} = params;
|
||||
const newParams = {
|
||||
convertToShorts,
|
||||
degPrecision,
|
||||
floatPrecision,
|
||||
transformPrecision,
|
||||
matrixToTransform,
|
||||
shortTranslate,
|
||||
shortScale,
|
||||
shortRotate,
|
||||
removeUseless,
|
||||
collapseIntoOne,
|
||||
leadingZero,
|
||||
negativeExtraSpace,
|
||||
};
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
// transform
|
||||
if (item.hasAttr('transform')) {
|
||||
convertTransform(item, 'transform', params);
|
||||
if (node.attributes.transform != null) {
|
||||
convertTransform(node, 'transform', newParams);
|
||||
}
|
||||
|
||||
// gradientTransform
|
||||
if (item.hasAttr('gradientTransform')) {
|
||||
convertTransform(item, 'gradientTransform', params);
|
||||
if (node.attributes.gradientTransform != null) {
|
||||
convertTransform(node, 'gradientTransform', newParams);
|
||||
}
|
||||
|
||||
// patternTransform
|
||||
if (item.hasAttr('patternTransform')) {
|
||||
convertTransform(item, 'patternTransform', params);
|
||||
if (node.attributes.patternTransform != null) {
|
||||
convertTransform(node, 'patternTransform', newParams);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* convertToShorts: boolean,
|
||||
* degPrecision?: number,
|
||||
* floatPrecision: number,
|
||||
* transformPrecision: number,
|
||||
* matrixToTransform: boolean,
|
||||
* shortTranslate: boolean,
|
||||
* shortScale: boolean,
|
||||
* shortRotate: boolean,
|
||||
* removeUseless: boolean,
|
||||
* collapseIntoOne: boolean,
|
||||
* leadingZero: boolean,
|
||||
* negativeExtraSpace: boolean,
|
||||
* }} TransformParams
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {{ name: string, data: Array<number> }} TransformItem
|
||||
*/
|
||||
|
||||
/**
|
||||
* Main function.
|
||||
*
|
||||
* @param {Object} item input item
|
||||
* @param {String} attrName attribute name
|
||||
* @param {Object} params plugin params
|
||||
* @type {(item: XastElement, attrName: string, params: TransformParams) => void}
|
||||
*/
|
||||
function convertTransform(item, attrName, params) {
|
||||
var data = transform2js(item.attr(attrName).value);
|
||||
params = definePrecision(data, params);
|
||||
const convertTransform = (item, attrName, params) => {
|
||||
let data = transform2js(item.attributes[attrName]);
|
||||
params = definePrecision(data, params);
|
||||
|
||||
if (params.collapseIntoOne && data.length > 1) {
|
||||
data = [transformsMultiply(data)];
|
||||
}
|
||||
if (params.collapseIntoOne && data.length > 1) {
|
||||
data = [transformsMultiply(data)];
|
||||
}
|
||||
|
||||
if (params.convertToShorts) {
|
||||
data = convertToShorts(data, params);
|
||||
} else {
|
||||
data.forEach(roundTransform);
|
||||
}
|
||||
if (params.convertToShorts) {
|
||||
data = convertToShorts(data, params);
|
||||
} else {
|
||||
data.forEach((item) => roundTransform(item, params));
|
||||
}
|
||||
|
||||
if (params.removeUseless) {
|
||||
data = removeUseless(data);
|
||||
}
|
||||
if (params.removeUseless) {
|
||||
data = removeUseless(data);
|
||||
}
|
||||
|
||||
if (data.length) {
|
||||
item.attr(attrName).value = js2transform(data, params);
|
||||
} else {
|
||||
item.removeAttr(attrName);
|
||||
}
|
||||
}
|
||||
if (data.length) {
|
||||
item.attributes[attrName] = js2transform(data, params);
|
||||
} else {
|
||||
delete item.attributes[attrName];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines precision to work with certain parts.
|
||||
@@ -106,259 +149,284 @@ function convertTransform(item, attrName, params) {
|
||||
* degPrecision - for rotate and skew. By default it's equal to (rougly)
|
||||
* transformPrecision - 2 or floatPrecision whichever is lower. Can be set in params.
|
||||
*
|
||||
* @param {Array} transforms input array
|
||||
* @param {Object} params plugin params
|
||||
* @return {Array} output array
|
||||
* @type {(data: Array<TransformItem>, params: TransformParams) => TransformParams}
|
||||
*
|
||||
* clone params so it don't affect other elements transformations.
|
||||
*/
|
||||
function definePrecision(data, params) {
|
||||
/* jshint validthis: true */
|
||||
var matrixData = data.reduce(getMatrixData, []),
|
||||
significantDigits = params.transformPrecision;
|
||||
|
||||
// Clone params so it don't affect other elements transformations.
|
||||
params = EXTEND({}, params);
|
||||
|
||||
// Limit transform precision with matrix one. Calculating with larger precision doesn't add any value.
|
||||
if (matrixData.length) {
|
||||
params.transformPrecision = Math.min(params.transformPrecision,
|
||||
Math.max.apply(Math, matrixData.map(floatDigits)) || params.transformPrecision);
|
||||
|
||||
significantDigits = Math.max.apply(Math, matrixData.map(function(n) {
|
||||
return String(n).replace(/\D+/g, '').length; // Number of digits in a number. 123.45 → 5
|
||||
}));
|
||||
const definePrecision = (data, { ...newParams }) => {
|
||||
const matrixData = [];
|
||||
for (const item of data) {
|
||||
if (item.name == 'matrix') {
|
||||
matrixData.push(...item.data.slice(0, 4));
|
||||
}
|
||||
// No sense in angle precision more then number of significant digits in matrix.
|
||||
if (!('degPrecision' in params)) {
|
||||
params.degPrecision = Math.max(0, Math.min(params.floatPrecision, significantDigits - 2));
|
||||
}
|
||||
|
||||
floatRound = params.floatPrecision >= 1 && params.floatPrecision < 20 ?
|
||||
smartRound.bind(this, params.floatPrecision) :
|
||||
round;
|
||||
degRound = params.degPrecision >= 1 && params.floatPrecision < 20 ?
|
||||
smartRound.bind(this, params.degPrecision) :
|
||||
round;
|
||||
transformRound = params.transformPrecision >= 1 && params.floatPrecision < 20 ?
|
||||
smartRound.bind(this, params.transformPrecision) :
|
||||
round;
|
||||
|
||||
return params;
|
||||
}
|
||||
}
|
||||
let significantDigits = newParams.transformPrecision;
|
||||
// Limit transform precision with matrix one. Calculating with larger precision doesn't add any value.
|
||||
if (matrixData.length) {
|
||||
newParams.transformPrecision = Math.min(
|
||||
newParams.transformPrecision,
|
||||
Math.max.apply(Math, matrixData.map(floatDigits)) ||
|
||||
newParams.transformPrecision
|
||||
);
|
||||
significantDigits = Math.max.apply(
|
||||
Math,
|
||||
matrixData.map(
|
||||
(n) => n.toString().replace(/\D+/g, '').length // Number of digits in a number. 123.45 → 5
|
||||
)
|
||||
);
|
||||
}
|
||||
// No sense in angle precision more then number of significant digits in matrix.
|
||||
if (newParams.degPrecision == null) {
|
||||
newParams.degPrecision = Math.max(
|
||||
0,
|
||||
Math.min(newParams.floatPrecision, significantDigits - 2)
|
||||
);
|
||||
}
|
||||
return newParams;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gathers four first matrix parameters.
|
||||
*
|
||||
* @param {Array} a array of data
|
||||
* @param {Object} transform
|
||||
* @return {Array} output array
|
||||
* @type {(data: Array<number>, params: TransformParams) => Array<number>}
|
||||
*/
|
||||
function getMatrixData(a, b) {
|
||||
return b.name == 'matrix' ? a.concat(b.data.slice(0, 4)) : a;
|
||||
}
|
||||
const degRound = (data, params) => {
|
||||
if (
|
||||
params.degPrecision != null &&
|
||||
params.degPrecision >= 1 &&
|
||||
params.floatPrecision < 20
|
||||
) {
|
||||
return smartRound(params.degPrecision, data);
|
||||
} else {
|
||||
return round(data);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* @type {(data: Array<number>, params: TransformParams) => Array<number>}
|
||||
*/
|
||||
const floatRound = (data, params) => {
|
||||
if (params.floatPrecision >= 1 && params.floatPrecision < 20) {
|
||||
return smartRound(params.floatPrecision, data);
|
||||
} else {
|
||||
return round(data);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(data: Array<number>, params: TransformParams) => Array<number>}
|
||||
*/
|
||||
const transformRound = (data, params) => {
|
||||
if (params.transformPrecision >= 1 && params.floatPrecision < 20) {
|
||||
return smartRound(params.transformPrecision, data);
|
||||
} else {
|
||||
return round(data);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns number of digits after the point. 0.125 → 3
|
||||
*
|
||||
* @type {(n: number) => number}
|
||||
*/
|
||||
function floatDigits(n) {
|
||||
return (n = String(n)).slice(n.indexOf('.')).length - 1;
|
||||
}
|
||||
const floatDigits = (n) => {
|
||||
const str = n.toString();
|
||||
return str.slice(str.indexOf('.')).length - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert transforms to the shorthand alternatives.
|
||||
*
|
||||
* @param {Array} transforms input array
|
||||
* @param {Object} params plugin params
|
||||
* @return {Array} output array
|
||||
* @type {(transforms: Array<TransformItem>, params: TransformParams) => Array<TransformItem>}
|
||||
*/
|
||||
function convertToShorts(transforms, params) {
|
||||
|
||||
for(var i = 0; i < transforms.length; i++) {
|
||||
|
||||
var transform = transforms[i];
|
||||
|
||||
// convert matrix to the short aliases
|
||||
if (
|
||||
params.matrixToTransform &&
|
||||
transform.name === 'matrix'
|
||||
) {
|
||||
var decomposed = matrixToTransform(transform, params);
|
||||
if (decomposed != transform &&
|
||||
js2transform(decomposed, params).length <= js2transform([transform], params).length) {
|
||||
|
||||
transforms.splice.apply(transforms, [i, 1].concat(decomposed));
|
||||
}
|
||||
transform = transforms[i];
|
||||
}
|
||||
|
||||
// fixed-point numbers
|
||||
// 12.754997 → 12.755
|
||||
roundTransform(transform);
|
||||
|
||||
// convert long translate transform notation to the shorts one
|
||||
// translate(10 0) → translate(10)
|
||||
if (
|
||||
params.shortTranslate &&
|
||||
transform.name === 'translate' &&
|
||||
transform.data.length === 2 &&
|
||||
!transform.data[1]
|
||||
) {
|
||||
transform.data.pop();
|
||||
}
|
||||
|
||||
// convert long scale transform notation to the shorts one
|
||||
// scale(2 2) → scale(2)
|
||||
if (
|
||||
params.shortScale &&
|
||||
transform.name === 'scale' &&
|
||||
transform.data.length === 2 &&
|
||||
transform.data[0] === transform.data[1]
|
||||
) {
|
||||
transform.data.pop();
|
||||
}
|
||||
|
||||
// convert long rotate transform notation to the short one
|
||||
// translate(cx cy) rotate(a) translate(-cx -cy) → rotate(a cx cy)
|
||||
if (
|
||||
params.shortRotate &&
|
||||
transforms[i - 2] &&
|
||||
transforms[i - 2].name === 'translate' &&
|
||||
transforms[i - 1].name === 'rotate' &&
|
||||
transforms[i].name === 'translate' &&
|
||||
transforms[i - 2].data[0] === -transforms[i].data[0] &&
|
||||
transforms[i - 2].data[1] === -transforms[i].data[1]
|
||||
) {
|
||||
transforms.splice(i - 2, 3, {
|
||||
name: 'rotate',
|
||||
data: [
|
||||
transforms[i - 1].data[0],
|
||||
transforms[i - 2].data[0],
|
||||
transforms[i - 2].data[1]
|
||||
]
|
||||
});
|
||||
|
||||
// splice compensation
|
||||
i -= 2;
|
||||
|
||||
transform = transforms[i];
|
||||
}
|
||||
const convertToShorts = (transforms, params) => {
|
||||
for (var i = 0; i < transforms.length; i++) {
|
||||
var transform = transforms[i];
|
||||
|
||||
// convert matrix to the short aliases
|
||||
if (params.matrixToTransform && transform.name === 'matrix') {
|
||||
var decomposed = matrixToTransform(transform, params);
|
||||
if (
|
||||
js2transform(decomposed, params).length <=
|
||||
js2transform([transform], params).length
|
||||
) {
|
||||
transforms.splice(i, 1, ...decomposed);
|
||||
}
|
||||
transform = transforms[i];
|
||||
}
|
||||
|
||||
return transforms;
|
||||
// fixed-point numbers
|
||||
// 12.754997 → 12.755
|
||||
roundTransform(transform, params);
|
||||
|
||||
}
|
||||
// convert long translate transform notation to the shorts one
|
||||
// translate(10 0) → translate(10)
|
||||
if (
|
||||
params.shortTranslate &&
|
||||
transform.name === 'translate' &&
|
||||
transform.data.length === 2 &&
|
||||
!transform.data[1]
|
||||
) {
|
||||
transform.data.pop();
|
||||
}
|
||||
|
||||
// convert long scale transform notation to the shorts one
|
||||
// scale(2 2) → scale(2)
|
||||
if (
|
||||
params.shortScale &&
|
||||
transform.name === 'scale' &&
|
||||
transform.data.length === 2 &&
|
||||
transform.data[0] === transform.data[1]
|
||||
) {
|
||||
transform.data.pop();
|
||||
}
|
||||
|
||||
// convert long rotate transform notation to the short one
|
||||
// translate(cx cy) rotate(a) translate(-cx -cy) → rotate(a cx cy)
|
||||
if (
|
||||
params.shortRotate &&
|
||||
transforms[i - 2] &&
|
||||
transforms[i - 2].name === 'translate' &&
|
||||
transforms[i - 1].name === 'rotate' &&
|
||||
transforms[i].name === 'translate' &&
|
||||
transforms[i - 2].data[0] === -transforms[i].data[0] &&
|
||||
transforms[i - 2].data[1] === -transforms[i].data[1]
|
||||
) {
|
||||
transforms.splice(i - 2, 3, {
|
||||
name: 'rotate',
|
||||
data: [
|
||||
transforms[i - 1].data[0],
|
||||
transforms[i - 2].data[0],
|
||||
transforms[i - 2].data[1],
|
||||
],
|
||||
});
|
||||
|
||||
// splice compensation
|
||||
i -= 2;
|
||||
}
|
||||
}
|
||||
|
||||
return transforms;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove useless transforms.
|
||||
*
|
||||
* @param {Array} transforms input array
|
||||
* @return {Array} output array
|
||||
* @type {(trasforms: Array<TransformItem>) => Array<TransformItem>}
|
||||
*/
|
||||
function removeUseless(transforms) {
|
||||
const removeUseless = (transforms) => {
|
||||
return transforms.filter((transform) => {
|
||||
// translate(0), rotate(0[, cx, cy]), skewX(0), skewY(0)
|
||||
if (
|
||||
(['translate', 'rotate', 'skewX', 'skewY'].indexOf(transform.name) > -1 &&
|
||||
(transform.data.length == 1 || transform.name == 'rotate') &&
|
||||
!transform.data[0]) ||
|
||||
// translate(0, 0)
|
||||
(transform.name == 'translate' &&
|
||||
!transform.data[0] &&
|
||||
!transform.data[1]) ||
|
||||
// scale(1)
|
||||
(transform.name == 'scale' &&
|
||||
transform.data[0] == 1 &&
|
||||
(transform.data.length < 2 || transform.data[1] == 1)) ||
|
||||
// matrix(1 0 0 1 0 0)
|
||||
(transform.name == 'matrix' &&
|
||||
transform.data[0] == 1 &&
|
||||
transform.data[3] == 1 &&
|
||||
!(
|
||||
transform.data[1] ||
|
||||
transform.data[2] ||
|
||||
transform.data[4] ||
|
||||
transform.data[5]
|
||||
))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return transforms.filter(function(transform) {
|
||||
|
||||
// translate(0), rotate(0[, cx, cy]), skewX(0), skewY(0)
|
||||
if (
|
||||
['translate', 'rotate', 'skewX', 'skewY'].indexOf(transform.name) > -1 &&
|
||||
(transform.data.length == 1 || transform.name == 'rotate') &&
|
||||
!transform.data[0] ||
|
||||
|
||||
// translate(0, 0)
|
||||
transform.name == 'translate' &&
|
||||
!transform.data[0] &&
|
||||
!transform.data[1] ||
|
||||
|
||||
// scale(1)
|
||||
transform.name == 'scale' &&
|
||||
transform.data[0] == 1 &&
|
||||
(transform.data.length < 2 || transform.data[1] == 1) ||
|
||||
|
||||
// matrix(1 0 0 1 0 0)
|
||||
transform.name == 'matrix' &&
|
||||
transform.data[0] == 1 &&
|
||||
transform.data[3] == 1 &&
|
||||
!(transform.data[1] || transform.data[2] || transform.data[4] || transform.data[5])
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert transforms JS representation to string.
|
||||
*
|
||||
* @param {Array} transformJS JS representation array
|
||||
* @param {Object} params plugin params
|
||||
* @return {String} output string
|
||||
* @type {(transformJS: Array<TransformItem>, params: TransformParams) => string}
|
||||
*/
|
||||
function js2transform(transformJS, params) {
|
||||
const js2transform = (transformJS, params) => {
|
||||
var transformString = '';
|
||||
|
||||
var transformString = '';
|
||||
// collect output value string
|
||||
transformJS.forEach((transform) => {
|
||||
roundTransform(transform, params);
|
||||
transformString +=
|
||||
(transformString && ' ') +
|
||||
transform.name +
|
||||
'(' +
|
||||
cleanupOutData(transform.data, params) +
|
||||
')';
|
||||
});
|
||||
|
||||
// collect output value string
|
||||
transformJS.forEach(function(transform) {
|
||||
roundTransform(transform);
|
||||
transformString += (transformString && ' ') + transform.name + '(' + cleanupOutData(transform.data, params) + ')';
|
||||
});
|
||||
return transformString;
|
||||
};
|
||||
|
||||
return transformString;
|
||||
|
||||
}
|
||||
|
||||
function roundTransform(transform) {
|
||||
switch (transform.name) {
|
||||
case 'translate':
|
||||
transform.data = floatRound(transform.data);
|
||||
break;
|
||||
case 'rotate':
|
||||
transform.data = degRound(transform.data.slice(0, 1)).concat(floatRound(transform.data.slice(1)));
|
||||
break;
|
||||
case 'skewX':
|
||||
case 'skewY':
|
||||
transform.data = degRound(transform.data);
|
||||
break;
|
||||
case 'scale':
|
||||
transform.data = transformRound(transform.data);
|
||||
break;
|
||||
case 'matrix':
|
||||
transform.data = transformRound(transform.data.slice(0, 4)).concat(floatRound(transform.data.slice(4)));
|
||||
break;
|
||||
}
|
||||
return transform;
|
||||
}
|
||||
/**
|
||||
* @type {(transform: TransformItem, params: TransformParams) => TransformItem}
|
||||
*/
|
||||
const roundTransform = (transform, params) => {
|
||||
switch (transform.name) {
|
||||
case 'translate':
|
||||
transform.data = floatRound(transform.data, params);
|
||||
break;
|
||||
case 'rotate':
|
||||
transform.data = [
|
||||
...degRound(transform.data.slice(0, 1), params),
|
||||
...floatRound(transform.data.slice(1), params),
|
||||
];
|
||||
break;
|
||||
case 'skewX':
|
||||
case 'skewY':
|
||||
transform.data = degRound(transform.data, params);
|
||||
break;
|
||||
case 'scale':
|
||||
transform.data = transformRound(transform.data, params);
|
||||
break;
|
||||
case 'matrix':
|
||||
transform.data = [
|
||||
...transformRound(transform.data.slice(0, 4), params),
|
||||
...floatRound(transform.data.slice(4), params),
|
||||
];
|
||||
break;
|
||||
}
|
||||
return transform;
|
||||
};
|
||||
|
||||
/**
|
||||
* Rounds numbers in array.
|
||||
*
|
||||
* @param {Array} data input data array
|
||||
* @return {Array} output data array
|
||||
* @type {(data: Array<number>) => Array<number>}
|
||||
*/
|
||||
function round(data) {
|
||||
return data.map(Math.round);
|
||||
}
|
||||
const round = (data) => {
|
||||
return data.map(Math.round);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrease accuracy of floating-point numbers
|
||||
* in transforms keeping a specified number of decimals.
|
||||
* Smart rounds values like 2.349 to 2.35.
|
||||
*
|
||||
* @param {Number} fixed number of decimals
|
||||
* @param {Array} data input data array
|
||||
* @return {Array} output data array
|
||||
* @type {(precision: number, data: Array<number>) => Array<number>}
|
||||
*/
|
||||
function smartRound(precision, data) {
|
||||
for (var i = data.length, tolerance = +Math.pow(.1, precision).toFixed(precision); i--;) {
|
||||
if (data[i].toFixed(precision) != data[i]) {
|
||||
var rounded = +data[i].toFixed(precision - 1);
|
||||
data[i] = +Math.abs(rounded - data[i]).toFixed(precision + 1) >= tolerance ?
|
||||
+data[i].toFixed(precision) :
|
||||
rounded;
|
||||
}
|
||||
const smartRound = (precision, data) => {
|
||||
for (
|
||||
var i = data.length,
|
||||
tolerance = +Math.pow(0.1, precision).toFixed(precision);
|
||||
i--;
|
||||
|
||||
) {
|
||||
if (Number(data[i].toFixed(precision)) !== data[i]) {
|
||||
var rounded = +data[i].toFixed(precision - 1);
|
||||
data[i] =
|
||||
+Math.abs(rounded - data[i]).toFixed(precision + 1) >= tolerance
|
||||
? +data[i].toFixed(precision)
|
||||
: rounded;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
379
node_modules/svgo/plugins/inlineStyles.js
generated
vendored
Normal file
379
node_modules/svgo/plugins/inlineStyles.js
generated
vendored
Normal file
@@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('../lib/types').Specificity} Specificity
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
* @typedef {import('../lib/types').XastParent} XastParent
|
||||
*/
|
||||
|
||||
const csstree = require('css-tree');
|
||||
// @ts-ignore not defined in @types/csso
|
||||
const specificity = require('csso/lib/restructure/prepare/specificity');
|
||||
const stable = require('stable');
|
||||
const {
|
||||
visitSkip,
|
||||
querySelectorAll,
|
||||
detachNodeFromParent,
|
||||
} = require('../lib/xast.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'inlineStyles';
|
||||
exports.active = true;
|
||||
exports.description = 'inline styles (additional options)';
|
||||
|
||||
/**
|
||||
* Compares two selector specificities.
|
||||
* extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
|
||||
*
|
||||
* @type {(a: Specificity, b: Specificity) => number}
|
||||
*/
|
||||
const compareSpecificity = (a, b) => {
|
||||
for (var i = 0; i < 4; i += 1) {
|
||||
if (a[i] < b[i]) {
|
||||
return -1;
|
||||
} else if (a[i] > b[i]) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Moves + merges styles from style elements to element styles
|
||||
*
|
||||
* Options
|
||||
* onlyMatchedOnce (default: true)
|
||||
* inline only selectors that match once
|
||||
*
|
||||
* removeMatchedSelectors (default: true)
|
||||
* clean up matched selectors,
|
||||
* leave selectors that hadn't matched
|
||||
*
|
||||
* useMqs (default: ['', 'screen'])
|
||||
* what media queries to be used
|
||||
* empty string element for styles outside media queries
|
||||
*
|
||||
* usePseudos (default: [''])
|
||||
* what pseudo-classes/-elements to be used
|
||||
* empty string element for all non-pseudo-classes and/or -elements
|
||||
*
|
||||
* @author strarsis <strarsis@gmail.com>
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* onlyMatchedOnce?: boolean,
|
||||
* removeMatchedSelectors?: boolean,
|
||||
* useMqs?: Array<string>,
|
||||
* usePseudos?: Array<string>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = (root, params) => {
|
||||
const {
|
||||
onlyMatchedOnce = true,
|
||||
removeMatchedSelectors = true,
|
||||
useMqs = ['', 'screen'],
|
||||
usePseudos = [''],
|
||||
} = params;
|
||||
|
||||
/**
|
||||
* @type {Array<{ node: XastElement, parentNode: XastParent, cssAst: csstree.StyleSheet }>}
|
||||
*/
|
||||
const styles = [];
|
||||
/**
|
||||
* @type {Array<{
|
||||
* node: csstree.Selector,
|
||||
* item: csstree.ListItem<csstree.CssNode>,
|
||||
* rule: csstree.Rule,
|
||||
* matchedElements?: Array<XastElement>
|
||||
* }>}
|
||||
*/
|
||||
let selectors = [];
|
||||
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// skip <foreignObject /> content
|
||||
if (node.name === 'foreignObject') {
|
||||
return visitSkip;
|
||||
}
|
||||
// collect only non-empty <style /> elements
|
||||
if (node.name !== 'style' || node.children.length === 0) {
|
||||
return;
|
||||
}
|
||||
// values other than the empty string or text/css are not used
|
||||
if (
|
||||
node.attributes.type != null &&
|
||||
node.attributes.type !== '' &&
|
||||
node.attributes.type !== 'text/css'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// parse css in style element
|
||||
let cssText = '';
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'text' || child.type === 'cdata') {
|
||||
cssText += child.value;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @type {null | csstree.CssNode}
|
||||
*/
|
||||
let cssAst = null;
|
||||
try {
|
||||
cssAst = csstree.parse(cssText, {
|
||||
parseValue: false,
|
||||
parseCustomProperty: false,
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (cssAst.type === 'StyleSheet') {
|
||||
styles.push({ node, parentNode, cssAst });
|
||||
}
|
||||
|
||||
// collect selectors
|
||||
csstree.walk(cssAst, {
|
||||
visit: 'Selector',
|
||||
enter(node, item) {
|
||||
const atrule = this.atrule;
|
||||
const rule = this.rule;
|
||||
if (rule == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// skip media queries not included into useMqs param
|
||||
let mq = '';
|
||||
if (atrule != null) {
|
||||
mq = atrule.name;
|
||||
if (atrule.prelude != null) {
|
||||
mq += ` ${csstree.generate(atrule.prelude)}`;
|
||||
}
|
||||
}
|
||||
if (useMqs.includes(mq) === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {Array<{
|
||||
* item: csstree.ListItem<csstree.CssNode>,
|
||||
* list: csstree.List<csstree.CssNode>
|
||||
* }>}
|
||||
*/
|
||||
const pseudos = [];
|
||||
if (node.type === 'Selector') {
|
||||
node.children.each((childNode, childItem, childList) => {
|
||||
if (
|
||||
childNode.type === 'PseudoClassSelector' ||
|
||||
childNode.type === 'PseudoElementSelector'
|
||||
) {
|
||||
pseudos.push({ item: childItem, list: childList });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// skip pseudo classes and pseudo elements not includes into usePseudos param
|
||||
const pseudoSelectors = csstree.generate({
|
||||
type: 'Selector',
|
||||
children: new csstree.List().fromArray(
|
||||
pseudos.map((pseudo) => pseudo.item.data)
|
||||
),
|
||||
});
|
||||
if (usePseudos.includes(pseudoSelectors) === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// remove pseudo classes and elements to allow querySelector match elements
|
||||
// TODO this is not very accurate since some pseudo classes like first-child
|
||||
// are used for selection
|
||||
for (const pseudo of pseudos) {
|
||||
pseudo.list.remove(pseudo.item);
|
||||
}
|
||||
|
||||
selectors.push({ node, item, rule });
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
root: {
|
||||
exit: () => {
|
||||
if (styles.length === 0) {
|
||||
return;
|
||||
}
|
||||
// stable sort selectors
|
||||
const sortedSelectors = stable(selectors, (a, b) => {
|
||||
const aSpecificity = specificity(a.item.data);
|
||||
const bSpecificity = specificity(b.item.data);
|
||||
return compareSpecificity(aSpecificity, bSpecificity);
|
||||
}).reverse();
|
||||
|
||||
for (const selector of sortedSelectors) {
|
||||
// match selectors
|
||||
const selectorText = csstree.generate(selector.item.data);
|
||||
/**
|
||||
* @type {Array<XastElement>}
|
||||
*/
|
||||
const matchedElements = [];
|
||||
try {
|
||||
for (const node of querySelectorAll(root, selectorText)) {
|
||||
if (node.type === 'element') {
|
||||
matchedElements.push(node);
|
||||
}
|
||||
}
|
||||
} catch (selectError) {
|
||||
continue;
|
||||
}
|
||||
// nothing selected
|
||||
if (matchedElements.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// apply styles to matched elements
|
||||
// skip selectors that match more than once if option onlyMatchedOnce is enabled
|
||||
if (onlyMatchedOnce && matchedElements.length > 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// apply <style/> to matched elements
|
||||
for (const selectedEl of matchedElements) {
|
||||
const styleDeclarationList = csstree.parse(
|
||||
selectedEl.attributes.style == null
|
||||
? ''
|
||||
: selectedEl.attributes.style,
|
||||
{
|
||||
context: 'declarationList',
|
||||
parseValue: false,
|
||||
}
|
||||
);
|
||||
if (styleDeclarationList.type !== 'DeclarationList') {
|
||||
continue;
|
||||
}
|
||||
const styleDeclarationItems = new Map();
|
||||
csstree.walk(styleDeclarationList, {
|
||||
visit: 'Declaration',
|
||||
enter(node, item) {
|
||||
styleDeclarationItems.set(node.property, item);
|
||||
},
|
||||
});
|
||||
// merge declarations
|
||||
csstree.walk(selector.rule, {
|
||||
visit: 'Declaration',
|
||||
enter(ruleDeclaration) {
|
||||
// existing inline styles have higher priority
|
||||
// no inline styles, external styles, external styles used
|
||||
// inline styles, external styles same priority as inline styles, inline styles used
|
||||
// inline styles, external styles higher priority than inline styles, external styles used
|
||||
const matchedItem = styleDeclarationItems.get(
|
||||
ruleDeclaration.property
|
||||
);
|
||||
const ruleDeclarationItem =
|
||||
styleDeclarationList.children.createItem(ruleDeclaration);
|
||||
if (matchedItem == null) {
|
||||
styleDeclarationList.children.append(ruleDeclarationItem);
|
||||
} else if (
|
||||
matchedItem.data.important !== true &&
|
||||
ruleDeclaration.important === true
|
||||
) {
|
||||
styleDeclarationList.children.replace(
|
||||
matchedItem,
|
||||
ruleDeclarationItem
|
||||
);
|
||||
styleDeclarationItems.set(
|
||||
ruleDeclaration.property,
|
||||
ruleDeclarationItem
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
selectedEl.attributes.style =
|
||||
csstree.generate(styleDeclarationList);
|
||||
}
|
||||
|
||||
if (
|
||||
removeMatchedSelectors &&
|
||||
matchedElements.length !== 0 &&
|
||||
selector.rule.prelude.type === 'SelectorList'
|
||||
) {
|
||||
// clean up matching simple selectors if option removeMatchedSelectors is enabled
|
||||
selector.rule.prelude.children.remove(selector.item);
|
||||
}
|
||||
selector.matchedElements = matchedElements;
|
||||
}
|
||||
|
||||
// no further processing required
|
||||
if (removeMatchedSelectors === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// clean up matched class + ID attribute values
|
||||
for (const selector of sortedSelectors) {
|
||||
if (selector.matchedElements == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (onlyMatchedOnce && selector.matchedElements.length > 1) {
|
||||
// skip selectors that match more than once if option onlyMatchedOnce is enabled
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const selectedEl of selector.matchedElements) {
|
||||
// class
|
||||
const classList = new Set(
|
||||
selectedEl.attributes.class == null
|
||||
? null
|
||||
: selectedEl.attributes.class.split(' ')
|
||||
);
|
||||
const firstSubSelector = selector.node.children.first();
|
||||
if (
|
||||
firstSubSelector != null &&
|
||||
firstSubSelector.type === 'ClassSelector'
|
||||
) {
|
||||
classList.delete(firstSubSelector.name);
|
||||
}
|
||||
if (classList.size === 0) {
|
||||
delete selectedEl.attributes.class;
|
||||
} else {
|
||||
selectedEl.attributes.class = Array.from(classList).join(' ');
|
||||
}
|
||||
|
||||
// ID
|
||||
if (
|
||||
firstSubSelector != null &&
|
||||
firstSubSelector.type === 'IdSelector'
|
||||
) {
|
||||
if (selectedEl.attributes.id === firstSubSelector.name) {
|
||||
delete selectedEl.attributes.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const style of styles) {
|
||||
csstree.walk(style.cssAst, {
|
||||
visit: 'Rule',
|
||||
enter: function (node, item, list) {
|
||||
// clean up <style/> rulesets without any css selectors left
|
||||
if (
|
||||
node.type === 'Rule' &&
|
||||
node.prelude.type === 'SelectorList' &&
|
||||
node.prelude.children.isEmpty()
|
||||
) {
|
||||
list.remove(item);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (style.cssAst.children.isEmpty()) {
|
||||
// remove emtpy style element
|
||||
detachNodeFromParent(style.node, style.parentNode);
|
||||
} else {
|
||||
// update style element if any styles left
|
||||
const firstChild = style.node.children[0];
|
||||
if (firstChild.type === 'text' || firstChild.type === 'cdata') {
|
||||
firstChild.value = csstree.generate(style.cssAst);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
133
node_modules/svgo/plugins/mergePaths.js
generated
vendored
133
node_modules/svgo/plugins/mergePaths.js
generated
vendored
@@ -1,71 +1,104 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { collectStylesheet, computeStyle } = require('../lib/style.js');
|
||||
const { path2js, js2path, intersects } = require('./_path.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'mergePaths';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'merges multiple paths in one if possible';
|
||||
|
||||
exports.params = {
|
||||
collapseRepeated: true,
|
||||
leadingZero: true,
|
||||
negativeExtraSpace: true
|
||||
};
|
||||
|
||||
var path2js = require('./_path.js').path2js,
|
||||
js2path = require('./_path.js').js2path,
|
||||
intersects = require('./_path.js').intersects;
|
||||
|
||||
/**
|
||||
* Merge multiple Paths into one.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich, Lev Solntsev
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* force?: boolean,
|
||||
* floatPrecision?: number,
|
||||
* noSpaceAfterFlags?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (root, params) => {
|
||||
const {
|
||||
force = false,
|
||||
floatPrecision,
|
||||
noSpaceAfterFlags = false, // a20 60 45 0 1 30 20 → a20 60 45 0130 20
|
||||
} = params;
|
||||
const stylesheet = collectStylesheet(root);
|
||||
|
||||
if (!item.isElem() || item.isEmpty()) return;
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
let prevChild = null;
|
||||
|
||||
var prevContentItem = null,
|
||||
prevContentItemKeys = null;
|
||||
for (const child of node.children) {
|
||||
// skip if previous element is not path or contains animation elements
|
||||
if (
|
||||
prevChild == null ||
|
||||
prevChild.type !== 'element' ||
|
||||
prevChild.name !== 'path' ||
|
||||
prevChild.children.length !== 0 ||
|
||||
prevChild.attributes.d == null
|
||||
) {
|
||||
prevChild = child;
|
||||
continue;
|
||||
}
|
||||
|
||||
item.content = item.content.filter(function(contentItem) {
|
||||
// skip if element is not path or contains animation elements
|
||||
if (
|
||||
child.type !== 'element' ||
|
||||
child.name !== 'path' ||
|
||||
child.children.length !== 0 ||
|
||||
child.attributes.d == null
|
||||
) {
|
||||
prevChild = child;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (prevContentItem &&
|
||||
prevContentItem.isElem('path') &&
|
||||
prevContentItem.isEmpty() &&
|
||||
prevContentItem.hasAttr('d') &&
|
||||
contentItem.isElem('path') &&
|
||||
contentItem.isEmpty() &&
|
||||
contentItem.hasAttr('d')
|
||||
) {
|
||||
// preserve paths with markers
|
||||
const computedStyle = computeStyle(stylesheet, child);
|
||||
if (
|
||||
computedStyle['marker-start'] ||
|
||||
computedStyle['marker-mid'] ||
|
||||
computedStyle['marker-end']
|
||||
) {
|
||||
prevChild = child;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!prevContentItemKeys) {
|
||||
prevContentItemKeys = Object.keys(prevContentItem.attrs);
|
||||
const prevChildAttrs = Object.keys(prevChild.attributes);
|
||||
const childAttrs = Object.keys(child.attributes);
|
||||
let attributesAreEqual = prevChildAttrs.length === childAttrs.length;
|
||||
for (const name of childAttrs) {
|
||||
if (name !== 'd') {
|
||||
if (
|
||||
prevChild.attributes[name] == null ||
|
||||
prevChild.attributes[name] !== child.attributes[name]
|
||||
) {
|
||||
attributesAreEqual = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
const prevPathJS = path2js(prevChild);
|
||||
const curPathJS = path2js(child);
|
||||
|
||||
var contentItemAttrs = Object.keys(contentItem.attrs),
|
||||
equalData = prevContentItemKeys.length == contentItemAttrs.length &&
|
||||
contentItemAttrs.every(function(key) {
|
||||
return key == 'd' ||
|
||||
prevContentItem.hasAttr(key) &&
|
||||
prevContentItem.attr(key).value == contentItem.attr(key).value;
|
||||
}),
|
||||
prevPathJS = path2js(prevContentItem),
|
||||
curPathJS = path2js(contentItem);
|
||||
if (
|
||||
attributesAreEqual &&
|
||||
(force || !intersects(prevPathJS, curPathJS))
|
||||
) {
|
||||
js2path(prevChild, prevPathJS.concat(curPathJS), {
|
||||
floatPrecision,
|
||||
noSpaceAfterFlags,
|
||||
});
|
||||
detachNodeFromParent(child, node);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (equalData && !intersects(prevPathJS, curPathJS)) {
|
||||
js2path(prevContentItem, prevPathJS.concat(curPathJS), params);
|
||||
return false;
|
||||
}
|
||||
prevChild = child;
|
||||
}
|
||||
|
||||
prevContentItem = contentItem;
|
||||
prevContentItemKeys = null;
|
||||
return true;
|
||||
|
||||
});
|
||||
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
93
node_modules/svgo/plugins/mergeStyles.js
generated
vendored
Normal file
93
node_modules/svgo/plugins/mergeStyles.js
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
*/
|
||||
|
||||
const { visitSkip, detachNodeFromParent } = require('../lib/xast.js');
|
||||
const JSAPI = require('../lib/svgo/jsAPI.js');
|
||||
|
||||
exports.name = 'mergeStyles';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
exports.description = 'merge multiple style elements into one';
|
||||
|
||||
/**
|
||||
* Merge multiple style elements into one.
|
||||
*
|
||||
* @author strarsis <strarsis@gmail.com>
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = () => {
|
||||
/**
|
||||
* @type {null | XastElement}
|
||||
*/
|
||||
let firstStyleElement = null;
|
||||
let collectedStyles = '';
|
||||
let styleContentType = 'text';
|
||||
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// skip <foreignObject> content
|
||||
if (node.name === 'foreignObject') {
|
||||
return visitSkip;
|
||||
}
|
||||
|
||||
// collect style elements
|
||||
if (node.name !== 'style') {
|
||||
return;
|
||||
}
|
||||
|
||||
// skip <style> with invalid type attribute
|
||||
if (
|
||||
node.attributes.type != null &&
|
||||
node.attributes.type !== '' &&
|
||||
node.attributes.type !== 'text/css'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// extract style element content
|
||||
let css = '';
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'text') {
|
||||
css += child.value;
|
||||
}
|
||||
if (child.type === 'cdata') {
|
||||
styleContentType = 'cdata';
|
||||
css += child.value;
|
||||
}
|
||||
}
|
||||
|
||||
// remove empty style elements
|
||||
if (css.trim().length === 0) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// collect css and wrap with media query if present in attribute
|
||||
if (node.attributes.media == null) {
|
||||
collectedStyles += css;
|
||||
} else {
|
||||
collectedStyles += `@media ${node.attributes.media}{${css}}`;
|
||||
delete node.attributes.media;
|
||||
}
|
||||
|
||||
// combine collected styles in the first style element
|
||||
if (firstStyleElement == null) {
|
||||
firstStyleElement = node;
|
||||
} else {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
firstStyleElement.children = [
|
||||
new JSAPI(
|
||||
{ type: styleContentType, value: collectedStyles },
|
||||
firstStyleElement
|
||||
),
|
||||
];
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
167
node_modules/svgo/plugins/minifyStyles.js
generated
vendored
Executable file → Normal file
167
node_modules/svgo/plugins/minifyStyles.js
generated
vendored
Executable file → Normal file
@@ -1,45 +1,148 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
*/
|
||||
|
||||
const csso = require('csso');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'minifyStyles';
|
||||
exports.active = true;
|
||||
|
||||
exports.params = {
|
||||
svgo: {}
|
||||
};
|
||||
|
||||
exports.description = 'minifies existing styles in svg';
|
||||
|
||||
var csso = require('csso');
|
||||
exports.description =
|
||||
'minifies styles and removes unused styles based on usage data';
|
||||
|
||||
/**
|
||||
* 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>
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<csso.MinifyOptions & Omit<csso.CompressOptions, 'usage'> & {
|
||||
* usage?: boolean | {
|
||||
* force?: boolean,
|
||||
* ids?: boolean,
|
||||
* classes?: boolean,
|
||||
* tags?: boolean
|
||||
* }
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, svgoOptions) {
|
||||
exports.fn = (_root, { usage, ...params }) => {
|
||||
let enableTagsUsage = true;
|
||||
let enableIdsUsage = true;
|
||||
let enableClassesUsage = true;
|
||||
// force to use usage data even if it unsafe (document contains <script> or on* attributes)
|
||||
let forceUsageDeoptimized = false;
|
||||
if (typeof usage === 'boolean') {
|
||||
enableTagsUsage = usage;
|
||||
enableIdsUsage = usage;
|
||||
enableClassesUsage = usage;
|
||||
} else if (usage) {
|
||||
enableTagsUsage = usage.tags == null ? true : usage.tags;
|
||||
enableIdsUsage = usage.ids == null ? true : usage.ids;
|
||||
enableClassesUsage = usage.classes == null ? true : usage.classes;
|
||||
forceUsageDeoptimized = usage.force == null ? false : usage.force;
|
||||
}
|
||||
/**
|
||||
* @type {Array<XastElement>}
|
||||
*/
|
||||
const styleElements = [];
|
||||
/**
|
||||
* @type {Array<XastElement>}
|
||||
*/
|
||||
const elementsWithStyleAttributes = [];
|
||||
let deoptimized = false;
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const tagsUsage = new Set();
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const idsUsage = new Set();
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const classesUsage = new Set();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
// detect deoptimisations
|
||||
if (node.name === 'script') {
|
||||
deoptimized = true;
|
||||
}
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.startsWith('on')) {
|
||||
deoptimized = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// collect tags, ids and classes usage
|
||||
tagsUsage.add(node.name);
|
||||
if (node.attributes.id != null) {
|
||||
idsUsage.add(node.attributes.id);
|
||||
}
|
||||
if (node.attributes.class != null) {
|
||||
for (const className of node.attributes.class.split(/\s+/)) {
|
||||
classesUsage.add(className);
|
||||
}
|
||||
}
|
||||
// collect style elements or elements with style attribute
|
||||
if (node.name === 'style' && node.children.length !== 0) {
|
||||
styleElements.push(node);
|
||||
} else if (node.attributes.style != null) {
|
||||
elementsWithStyleAttributes.push(node);
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
return item;
|
||||
root: {
|
||||
exit: () => {
|
||||
/**
|
||||
* @type {csso.Usage}
|
||||
*/
|
||||
const cssoUsage = {};
|
||||
if (deoptimized === false || forceUsageDeoptimized === true) {
|
||||
if (enableTagsUsage && tagsUsage.size !== 0) {
|
||||
cssoUsage.tags = Array.from(tagsUsage);
|
||||
}
|
||||
if (enableIdsUsage && idsUsage.size !== 0) {
|
||||
cssoUsage.ids = Array.from(idsUsage);
|
||||
}
|
||||
if (enableClassesUsage && classesUsage.size !== 0) {
|
||||
cssoUsage.classes = Array.from(classesUsage);
|
||||
}
|
||||
}
|
||||
// minify style elements
|
||||
for (const node of styleElements) {
|
||||
if (
|
||||
node.children[0].type === 'text' ||
|
||||
node.children[0].type === 'cdata'
|
||||
) {
|
||||
const cssText = node.children[0].value;
|
||||
const minified = csso.minify(cssText, {
|
||||
...params,
|
||||
usage: cssoUsage,
|
||||
}).css;
|
||||
// preserve cdata if necessary
|
||||
// TODO split cdata -> text optimisation into separate plugin
|
||||
if (cssText.indexOf('>') >= 0 || cssText.indexOf('<') >= 0) {
|
||||
node.children[0].type = 'cdata';
|
||||
node.children[0].value = minified;
|
||||
} else {
|
||||
node.children[0].type = 'text';
|
||||
node.children[0].value = minified;
|
||||
}
|
||||
}
|
||||
}
|
||||
// minify style attributes
|
||||
for (const node of elementsWithStyleAttributes) {
|
||||
// style attribute
|
||||
const elemStyle = node.attributes.style;
|
||||
node.attributes.style = csso.minifyBlock(elemStyle, {
|
||||
...params,
|
||||
}).css;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
186
node_modules/svgo/plugins/moveElemsAttrsToGroup.js
generated
vendored
186
node_modules/svgo/plugins/moveElemsAttrsToGroup.js
generated
vendored
@@ -1,17 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItemReverse';
|
||||
const { visit } = require('../lib/xast.js');
|
||||
const { inheritableAttrs, pathElems } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'moveElemsAttrsToGroup';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'moves elements attributes to the existing group wrapper';
|
||||
|
||||
var inheritableAttrs = require('./_collections').inheritableAttrs,
|
||||
pathElems = require('./_collections.js').pathElems;
|
||||
exports.description = 'Move common attributes of group children to the group';
|
||||
|
||||
/**
|
||||
* Collapse content's intersected and inheritable
|
||||
* attributes to the existing group wrapper.
|
||||
* Move common attributes of group children to the group
|
||||
*
|
||||
* @example
|
||||
* <g attr1="val1">
|
||||
@@ -28,99 +26,105 @@ var inheritableAttrs = require('./_collections').inheritableAttrs,
|
||||
* <circle attr3="val3"/>
|
||||
* </g>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.isElem('g') && !item.isEmpty() && item.content.length > 1) {
|
||||
|
||||
var intersection = {},
|
||||
hasTransform = false,
|
||||
hasClip = item.hasAttr('clip-path') || item.hasAttr('mask'),
|
||||
intersected = item.content.every(function(inner) {
|
||||
if (inner.isElem() && inner.hasAttr()) {
|
||||
// don't mess with possible styles (hack until CSS parsing is implemented)
|
||||
if (inner.hasAttr('class')) return false;
|
||||
if (!Object.keys(intersection).length) {
|
||||
intersection = inner.attrs;
|
||||
} else {
|
||||
intersection = intersectInheritableAttrs(intersection, inner.attrs);
|
||||
|
||||
if (!intersection) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}),
|
||||
allPath = item.content.every(function(inner) {
|
||||
return inner.isElem(pathElems);
|
||||
});
|
||||
|
||||
if (intersected) {
|
||||
|
||||
item.content.forEach(function(g) {
|
||||
|
||||
for (var name in intersection) {
|
||||
|
||||
if (!allPath && !hasClip || name !== 'transform') {
|
||||
|
||||
g.removeAttr(name);
|
||||
|
||||
if (name === 'transform') {
|
||||
if (!hasTransform) {
|
||||
if (item.hasAttr('transform')) {
|
||||
item.attr('transform').value += ' ' + intersection[name].value;
|
||||
} else {
|
||||
item.addAttr(intersection[name]);
|
||||
}
|
||||
|
||||
hasTransform = true;
|
||||
}
|
||||
} else {
|
||||
item.addAttr(intersection[name]);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
exports.fn = (root) => {
|
||||
// find if any style element is present
|
||||
let deoptimizedWithStyles = false;
|
||||
visit(root, {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.name === 'style') {
|
||||
deoptimizedWithStyles = true;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
element: {
|
||||
exit: (node) => {
|
||||
// process only groups with more than 1 children
|
||||
if (node.name !== 'g' || node.children.length <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
// deoptimize the plugin when style elements are present
|
||||
// selectors may rely on id, classes or tag names
|
||||
if (deoptimizedWithStyles) {
|
||||
return;
|
||||
}
|
||||
|
||||
};
|
||||
/**
|
||||
* find common attributes in group children
|
||||
* @type {Map<string, string>}
|
||||
*/
|
||||
const commonAttributes = new Map();
|
||||
let initial = true;
|
||||
let everyChildIsPath = true;
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'element') {
|
||||
if (pathElems.includes(child.name) === false) {
|
||||
everyChildIsPath = false;
|
||||
}
|
||||
if (initial) {
|
||||
initial = false;
|
||||
// collect all inheritable attributes from first child element
|
||||
for (const [name, value] of Object.entries(child.attributes)) {
|
||||
// consider only inheritable attributes
|
||||
if (inheritableAttrs.includes(name)) {
|
||||
commonAttributes.set(name, value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// exclude uncommon attributes from initial list
|
||||
for (const [name, value] of commonAttributes) {
|
||||
if (child.attributes[name] !== value) {
|
||||
commonAttributes.delete(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Intersect inheritable attributes.
|
||||
*
|
||||
* @param {Object} a first attrs object
|
||||
* @param {Object} b second attrs object
|
||||
*
|
||||
* @return {Object} intersected attrs object
|
||||
*/
|
||||
function intersectInheritableAttrs(a, b) {
|
||||
|
||||
var c = {};
|
||||
|
||||
for (var n in a) {
|
||||
// preserve transform on children when group has clip-path or mask
|
||||
if (
|
||||
b.hasOwnProperty(n) &&
|
||||
inheritableAttrs.indexOf(n) > -1 &&
|
||||
a[n].name === b[n].name &&
|
||||
a[n].value === b[n].value &&
|
||||
a[n].prefix === b[n].prefix &&
|
||||
a[n].local === b[n].local
|
||||
node.attributes['clip-path'] != null ||
|
||||
node.attributes.mask != null
|
||||
) {
|
||||
c[n] = a[n];
|
||||
commonAttributes.delete('transform');
|
||||
}
|
||||
}
|
||||
|
||||
if (!Object.keys(c).length) return false;
|
||||
// preserve transform when all children are paths
|
||||
// so the transform could be applied to path data by other plugins
|
||||
if (everyChildIsPath) {
|
||||
commonAttributes.delete('transform');
|
||||
}
|
||||
|
||||
return c;
|
||||
// add common children attributes to group
|
||||
for (const [name, value] of commonAttributes) {
|
||||
if (name === 'transform') {
|
||||
if (node.attributes.transform != null) {
|
||||
node.attributes.transform = `${node.attributes.transform} ${value}`;
|
||||
} else {
|
||||
node.attributes.transform = value;
|
||||
}
|
||||
} else {
|
||||
node.attributes[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// delete common attributes from children
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'element') {
|
||||
for (const [name] of commonAttributes) {
|
||||
delete child.attributes[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
57
node_modules/svgo/plugins/moveGroupAttrsToElems.js
generated
vendored
57
node_modules/svgo/plugins/moveGroupAttrsToElems.js
generated
vendored
@@ -1,14 +1,16 @@
|
||||
'use strict';
|
||||
|
||||
const { pathElems, referencesProps } = require('./_collections.js');
|
||||
|
||||
exports.name = 'moveGroupAttrsToElems';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'moves some group attributes to the content elements';
|
||||
|
||||
var collections = require('./_collections.js'),
|
||||
pathElems = collections.pathElems.concat(['g', 'text']),
|
||||
referencesProps = collections.referencesProps;
|
||||
const pathElemsWithGroupsAndText = [...pathElems, 'g', 'text'];
|
||||
|
||||
/**
|
||||
* Move group attrs to the content elements.
|
||||
@@ -29,29 +31,32 @@ var collections = require('./_collections.js'),
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
// move group transform attr to content's pathElems
|
||||
if (
|
||||
item.isElem('g') &&
|
||||
item.hasAttr('transform') &&
|
||||
!item.isEmpty() &&
|
||||
!item.someAttr(function(attr) {
|
||||
return ~referencesProps.indexOf(attr.name) && ~attr.value.indexOf('url(');
|
||||
}) &&
|
||||
item.content.every(function(inner) {
|
||||
return inner.isElem(pathElems) && !inner.hasAttr('id');
|
||||
})
|
||||
) {
|
||||
item.content.forEach(function(inner) {
|
||||
if (inner.hasAttr('transform')) {
|
||||
inner.attr('transform').value = item.attr('transform').value + ' ' + inner.attr('transform').value;
|
||||
} else {
|
||||
inner.addAttr(item.attr('transform'));
|
||||
}
|
||||
});
|
||||
|
||||
item.removeAttr('transform');
|
||||
exports.fn = function (item) {
|
||||
// move group transform attr to content's pathElems
|
||||
if (
|
||||
item.type === 'element' &&
|
||||
item.name === 'g' &&
|
||||
item.children.length !== 0 &&
|
||||
item.attributes.transform != null &&
|
||||
Object.entries(item.attributes).some(
|
||||
([name, value]) =>
|
||||
referencesProps.includes(name) && value.includes('url(')
|
||||
) === false &&
|
||||
item.children.every(
|
||||
(inner) =>
|
||||
pathElemsWithGroupsAndText.includes(inner.name) &&
|
||||
inner.attributes.id == null
|
||||
)
|
||||
) {
|
||||
for (const inner of item.children) {
|
||||
const value = item.attributes.transform;
|
||||
if (inner.attributes.transform != null) {
|
||||
inner.attributes.transform = value + ' ' + inner.attributes.transform;
|
||||
} else {
|
||||
inner.attributes.transform = value;
|
||||
}
|
||||
}
|
||||
|
||||
delete item.attributes.transform;
|
||||
}
|
||||
};
|
||||
|
||||
56
node_modules/svgo/plugins/plugins.js
generated
vendored
Normal file
56
node_modules/svgo/plugins/plugins.js
generated
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
// builtin presets
|
||||
exports['preset-default'] = require('./preset-default.js');
|
||||
|
||||
// builtin plugins
|
||||
exports.addAttributesToSVGElement = require('./addAttributesToSVGElement.js');
|
||||
exports.addClassesToSVGElement = require('./addClassesToSVGElement.js');
|
||||
exports.cleanupAttrs = require('./cleanupAttrs.js');
|
||||
exports.cleanupEnableBackground = require('./cleanupEnableBackground.js');
|
||||
exports.cleanupIDs = require('./cleanupIDs.js');
|
||||
exports.cleanupListOfValues = require('./cleanupListOfValues.js');
|
||||
exports.cleanupNumericValues = require('./cleanupNumericValues.js');
|
||||
exports.collapseGroups = require('./collapseGroups.js');
|
||||
exports.convertColors = require('./convertColors.js');
|
||||
exports.convertEllipseToCircle = require('./convertEllipseToCircle.js');
|
||||
exports.convertPathData = require('./convertPathData.js');
|
||||
exports.convertShapeToPath = require('./convertShapeToPath.js');
|
||||
exports.convertStyleToAttrs = require('./convertStyleToAttrs.js');
|
||||
exports.convertTransform = require('./convertTransform.js');
|
||||
exports.mergeStyles = require('./mergeStyles.js');
|
||||
exports.inlineStyles = require('./inlineStyles.js');
|
||||
exports.mergePaths = require('./mergePaths.js');
|
||||
exports.minifyStyles = require('./minifyStyles.js');
|
||||
exports.moveElemsAttrsToGroup = require('./moveElemsAttrsToGroup.js');
|
||||
exports.moveGroupAttrsToElems = require('./moveGroupAttrsToElems.js');
|
||||
exports.prefixIds = require('./prefixIds.js');
|
||||
exports.removeAttributesBySelector = require('./removeAttributesBySelector.js');
|
||||
exports.removeAttrs = require('./removeAttrs.js');
|
||||
exports.removeComments = require('./removeComments.js');
|
||||
exports.removeDesc = require('./removeDesc.js');
|
||||
exports.removeDimensions = require('./removeDimensions.js');
|
||||
exports.removeDoctype = require('./removeDoctype.js');
|
||||
exports.removeEditorsNSData = require('./removeEditorsNSData.js');
|
||||
exports.removeElementsByAttr = require('./removeElementsByAttr.js');
|
||||
exports.removeEmptyAttrs = require('./removeEmptyAttrs.js');
|
||||
exports.removeEmptyContainers = require('./removeEmptyContainers.js');
|
||||
exports.removeEmptyText = require('./removeEmptyText.js');
|
||||
exports.removeHiddenElems = require('./removeHiddenElems.js');
|
||||
exports.removeMetadata = require('./removeMetadata.js');
|
||||
exports.removeNonInheritableGroupAttrs = require('./removeNonInheritableGroupAttrs.js');
|
||||
exports.removeOffCanvasPaths = require('./removeOffCanvasPaths.js');
|
||||
exports.removeRasterImages = require('./removeRasterImages.js');
|
||||
exports.removeScriptElement = require('./removeScriptElement.js');
|
||||
exports.removeStyleElement = require('./removeStyleElement.js');
|
||||
exports.removeTitle = require('./removeTitle.js');
|
||||
exports.removeUnknownsAndDefaults = require('./removeUnknownsAndDefaults.js');
|
||||
exports.removeUnusedNS = require('./removeUnusedNS.js');
|
||||
exports.removeUselessDefs = require('./removeUselessDefs.js');
|
||||
exports.removeUselessStrokeAndFill = require('./removeUselessStrokeAndFill.js');
|
||||
exports.removeViewBox = require('./removeViewBox.js');
|
||||
exports.removeXMLNS = require('./removeXMLNS.js');
|
||||
exports.removeXMLProcInst = require('./removeXMLProcInst.js');
|
||||
exports.reusePaths = require('./reusePaths.js');
|
||||
exports.sortAttrs = require('./sortAttrs.js');
|
||||
exports.sortDefsChildren = require('./sortDefsChildren.js');
|
||||
241
node_modules/svgo/plugins/prefixIds.js
generated
vendored
Normal file
241
node_modules/svgo/plugins/prefixIds.js
generated
vendored
Normal file
@@ -0,0 +1,241 @@
|
||||
'use strict';
|
||||
|
||||
const csstree = require('css-tree');
|
||||
const { referencesProps } = require('./_collections.js');
|
||||
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
* @typedef {import('../lib/types').PluginInfo} PluginInfo
|
||||
*/
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'prefixIds';
|
||||
exports.active = false;
|
||||
exports.description = 'prefix IDs';
|
||||
|
||||
/**
|
||||
* extract basename from path
|
||||
* @type {(path: string) => string}
|
||||
*/
|
||||
const getBasename = (path) => {
|
||||
// extract everything after latest slash or backslash
|
||||
const matched = path.match(/[/\\]?([^/\\]+)$/);
|
||||
if (matched) {
|
||||
return matched[1];
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
/**
|
||||
* escapes a string for being used as ID
|
||||
* @type {(string: string) => string}
|
||||
*/
|
||||
const escapeIdentifierName = (str) => {
|
||||
return str.replace(/[. ]/g, '_');
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {(string: string) => string}
|
||||
*/
|
||||
const unquote = (string) => {
|
||||
if (
|
||||
(string.startsWith('"') && string.endsWith('"')) ||
|
||||
(string.startsWith("'") && string.endsWith("'"))
|
||||
) {
|
||||
return string.slice(1, -1);
|
||||
}
|
||||
return string;
|
||||
};
|
||||
|
||||
/**
|
||||
* prefix an ID
|
||||
* @type {(prefix: string, name: string) => string}
|
||||
*/
|
||||
const prefixId = (prefix, value) => {
|
||||
if (value.startsWith(prefix)) {
|
||||
return value;
|
||||
}
|
||||
return prefix + value;
|
||||
};
|
||||
|
||||
/**
|
||||
* prefix an #ID
|
||||
* @type {(prefix: string, name: string) => string | null}
|
||||
*/
|
||||
const prefixReference = (prefix, value) => {
|
||||
if (value.startsWith('#')) {
|
||||
return '#' + prefixId(prefix, value.slice(1));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prefixes identifiers
|
||||
*
|
||||
* @author strarsis <strarsis@gmail.com>
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* prefix?: boolean | string | ((node: XastElement, info: PluginInfo) => string),
|
||||
* delim?: string,
|
||||
* prefixIds?: boolean,
|
||||
* prefixClassNames?: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = (_root, params, info) => {
|
||||
const { delim = '__', prefixIds = true, prefixClassNames = true } = params;
|
||||
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
/**
|
||||
* prefix, from file name or option
|
||||
* @type {string}
|
||||
*/
|
||||
let prefix = 'prefix' + delim;
|
||||
if (typeof params.prefix === 'function') {
|
||||
prefix = params.prefix(node, info) + delim;
|
||||
} else if (typeof params.prefix === 'string') {
|
||||
prefix = params.prefix + delim;
|
||||
} else if (params.prefix === false) {
|
||||
prefix = '';
|
||||
} else if (info.path != null && info.path.length > 0) {
|
||||
prefix = escapeIdentifierName(getBasename(info.path)) + delim;
|
||||
}
|
||||
|
||||
// prefix id/class selectors and url() references in styles
|
||||
if (node.name === 'style') {
|
||||
// skip empty <style/> elements
|
||||
if (node.children.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// parse styles
|
||||
let cssText = '';
|
||||
if (
|
||||
node.children[0].type === 'text' ||
|
||||
node.children[0].type === 'cdata'
|
||||
) {
|
||||
cssText = node.children[0].value;
|
||||
}
|
||||
/**
|
||||
* @type {null | csstree.CssNode}
|
||||
*/
|
||||
let cssAst = null;
|
||||
try {
|
||||
cssAst = csstree.parse(cssText, {
|
||||
parseValue: true,
|
||||
parseCustomProperty: false,
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
csstree.walk(cssAst, (node) => {
|
||||
// #ID, .class selectors
|
||||
if (
|
||||
(prefixIds && node.type === 'IdSelector') ||
|
||||
(prefixClassNames && node.type === 'ClassSelector')
|
||||
) {
|
||||
node.name = prefixId(prefix, node.name);
|
||||
return;
|
||||
}
|
||||
// url(...) references
|
||||
if (
|
||||
node.type === 'Url' &&
|
||||
node.value.value &&
|
||||
node.value.value.length > 0
|
||||
) {
|
||||
const prefixed = prefixReference(
|
||||
prefix,
|
||||
unquote(node.value.value)
|
||||
);
|
||||
if (prefixed != null) {
|
||||
node.value.value = prefixed;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// update styles
|
||||
if (
|
||||
node.children[0].type === 'text' ||
|
||||
node.children[0].type === 'cdata'
|
||||
) {
|
||||
node.children[0].value = csstree.generate(cssAst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// prefix an ID attribute value
|
||||
if (
|
||||
prefixIds &&
|
||||
node.attributes.id != null &&
|
||||
node.attributes.id.length !== 0
|
||||
) {
|
||||
node.attributes.id = prefixId(prefix, node.attributes.id);
|
||||
}
|
||||
|
||||
// prefix a class attribute value
|
||||
if (
|
||||
prefixClassNames &&
|
||||
node.attributes.class != null &&
|
||||
node.attributes.class.length !== 0
|
||||
) {
|
||||
node.attributes.class = node.attributes.class
|
||||
.split(/\s+/)
|
||||
.map((name) => prefixId(prefix, name))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
// prefix a href attribute value
|
||||
// xlink:href is deprecated, must be still supported
|
||||
for (const name of ['href', 'xlink:href']) {
|
||||
if (
|
||||
node.attributes[name] != null &&
|
||||
node.attributes[name].length !== 0
|
||||
) {
|
||||
const prefixed = prefixReference(prefix, node.attributes[name]);
|
||||
if (prefixed != null) {
|
||||
node.attributes[name] = prefixed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prefix an URL attribute value
|
||||
for (const name of referencesProps) {
|
||||
if (
|
||||
node.attributes[name] != null &&
|
||||
node.attributes[name].length !== 0
|
||||
) {
|
||||
node.attributes[name] = node.attributes[name].replace(
|
||||
/url\((.*?)\)/gi,
|
||||
(match, url) => {
|
||||
const prefixed = prefixReference(prefix, url);
|
||||
if (prefixed == null) {
|
||||
return match;
|
||||
}
|
||||
return `url(${prefixed})`;
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// prefix begin/end attribute value
|
||||
for (const name of ['begin', 'end']) {
|
||||
if (
|
||||
node.attributes[name] != null &&
|
||||
node.attributes[name].length !== 0
|
||||
) {
|
||||
const parts = node.attributes[name].split(/\s*;\s+/).map((val) => {
|
||||
if (val.endsWith('.end') || val.endsWith('.start')) {
|
||||
const [id, postfix] = val.split('.');
|
||||
return `${prefixId(prefix, id)}.${postfix}`;
|
||||
}
|
||||
return val;
|
||||
});
|
||||
node.attributes[name] = parts.join('; ');
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
80
node_modules/svgo/plugins/preset-default.js
generated
vendored
Normal file
80
node_modules/svgo/plugins/preset-default.js
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
'use strict';
|
||||
|
||||
const { createPreset } = require('../lib/svgo/plugins.js');
|
||||
|
||||
const removeDoctype = require('./removeDoctype.js');
|
||||
const removeXMLProcInst = require('./removeXMLProcInst.js');
|
||||
const removeComments = require('./removeComments.js');
|
||||
const removeMetadata = require('./removeMetadata.js');
|
||||
const removeEditorsNSData = require('./removeEditorsNSData.js');
|
||||
const cleanupAttrs = require('./cleanupAttrs.js');
|
||||
const mergeStyles = require('./mergeStyles.js');
|
||||
const inlineStyles = require('./inlineStyles.js');
|
||||
const minifyStyles = require('./minifyStyles.js');
|
||||
const cleanupIDs = require('./cleanupIDs.js');
|
||||
const removeUselessDefs = require('./removeUselessDefs.js');
|
||||
const cleanupNumericValues = require('./cleanupNumericValues.js');
|
||||
const convertColors = require('./convertColors.js');
|
||||
const removeUnknownsAndDefaults = require('./removeUnknownsAndDefaults.js');
|
||||
const removeNonInheritableGroupAttrs = require('./removeNonInheritableGroupAttrs.js');
|
||||
const removeUselessStrokeAndFill = require('./removeUselessStrokeAndFill.js');
|
||||
const removeViewBox = require('./removeViewBox.js');
|
||||
const cleanupEnableBackground = require('./cleanupEnableBackground.js');
|
||||
const removeHiddenElems = require('./removeHiddenElems.js');
|
||||
const removeEmptyText = require('./removeEmptyText.js');
|
||||
const convertShapeToPath = require('./convertShapeToPath.js');
|
||||
const convertEllipseToCircle = require('./convertEllipseToCircle.js');
|
||||
const moveElemsAttrsToGroup = require('./moveElemsAttrsToGroup.js');
|
||||
const moveGroupAttrsToElems = require('./moveGroupAttrsToElems.js');
|
||||
const collapseGroups = require('./collapseGroups.js');
|
||||
const convertPathData = require('./convertPathData.js');
|
||||
const convertTransform = require('./convertTransform.js');
|
||||
const removeEmptyAttrs = require('./removeEmptyAttrs.js');
|
||||
const removeEmptyContainers = require('./removeEmptyContainers.js');
|
||||
const mergePaths = require('./mergePaths.js');
|
||||
const removeUnusedNS = require('./removeUnusedNS.js');
|
||||
const sortDefsChildren = require('./sortDefsChildren.js');
|
||||
const removeTitle = require('./removeTitle.js');
|
||||
const removeDesc = require('./removeDesc.js');
|
||||
|
||||
const presetDefault = createPreset({
|
||||
name: 'presetDefault',
|
||||
plugins: [
|
||||
removeDoctype,
|
||||
removeXMLProcInst,
|
||||
removeComments,
|
||||
removeMetadata,
|
||||
removeEditorsNSData,
|
||||
cleanupAttrs,
|
||||
mergeStyles,
|
||||
inlineStyles,
|
||||
minifyStyles,
|
||||
cleanupIDs,
|
||||
removeUselessDefs,
|
||||
cleanupNumericValues,
|
||||
convertColors,
|
||||
removeUnknownsAndDefaults,
|
||||
removeNonInheritableGroupAttrs,
|
||||
removeUselessStrokeAndFill,
|
||||
removeViewBox,
|
||||
cleanupEnableBackground,
|
||||
removeHiddenElems,
|
||||
removeEmptyText,
|
||||
convertShapeToPath,
|
||||
convertEllipseToCircle,
|
||||
moveElemsAttrsToGroup,
|
||||
moveGroupAttrsToElems,
|
||||
collapseGroups,
|
||||
convertPathData,
|
||||
convertTransform,
|
||||
removeEmptyAttrs,
|
||||
removeEmptyContainers,
|
||||
mergePaths,
|
||||
removeUnusedNS,
|
||||
sortDefsChildren,
|
||||
removeTitle,
|
||||
removeDesc,
|
||||
],
|
||||
});
|
||||
|
||||
module.exports = presetDefault;
|
||||
99
node_modules/svgo/plugins/removeAttributesBySelector.js
generated
vendored
Normal file
99
node_modules/svgo/plugins/removeAttributesBySelector.js
generated
vendored
Normal file
@@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
|
||||
const { querySelectorAll } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeAttributesBySelector';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
exports.description =
|
||||
'removes attributes of elements that match a css selector';
|
||||
|
||||
/**
|
||||
* Removes attributes of elements that match a css selector.
|
||||
*
|
||||
* @example
|
||||
* <caption>A selector removing a single attribute</caption>
|
||||
* plugins: [
|
||||
* {
|
||||
* name: "removeAttributesBySelector",
|
||||
* params: {
|
||||
* selector: "[fill='#00ff00']"
|
||||
* attributes: "fill"
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
|
||||
* ↓
|
||||
* <rect x="0" y="0" width="100" height="100" stroke="#00ff00"/>
|
||||
*
|
||||
* <caption>A selector removing multiple attributes</caption>
|
||||
* plugins: [
|
||||
* {
|
||||
* name: "removeAttributesBySelector",
|
||||
* params: {
|
||||
* selector: "[fill='#00ff00']",
|
||||
* attributes: [
|
||||
* "fill",
|
||||
* "stroke"
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
|
||||
* ↓
|
||||
* <rect x="0" y="0" width="100" height="100"/>
|
||||
*
|
||||
* <caption>Multiple selectors removing attributes</caption>
|
||||
* plugins: [
|
||||
* {
|
||||
* name: "removeAttributesBySelector",
|
||||
* params: {
|
||||
* selectors: [
|
||||
* {
|
||||
* selector: "[fill='#00ff00']",
|
||||
* attributes: "fill"
|
||||
* },
|
||||
* {
|
||||
* selector: "#remove",
|
||||
* attributes: [
|
||||
* "stroke",
|
||||
* "id"
|
||||
* ]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* <rect x="0" y="0" width="100" height="100" fill="#00ff00" stroke="#00ff00"/>
|
||||
* ↓
|
||||
* <rect x="0" y="0" width="100" height="100"/>
|
||||
*
|
||||
* @link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|MDN CSS Selectors
|
||||
*
|
||||
* @author Bradley Mease
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<any>}
|
||||
*/
|
||||
exports.fn = (root, params) => {
|
||||
const selectors = Array.isArray(params.selectors)
|
||||
? params.selectors
|
||||
: [params];
|
||||
for (const { selector, attributes } of selectors) {
|
||||
const nodes = querySelectorAll(root, selector);
|
||||
for (const node of nodes) {
|
||||
if (node.type === 'element') {
|
||||
if (Array.isArray(attributes)) {
|
||||
for (const name of attributes) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
} else {
|
||||
delete node.attributes[attributes];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
162
node_modules/svgo/plugins/removeAttrs.js
generated
vendored
162
node_modules/svgo/plugins/removeAttrs.js
generated
vendored
@@ -1,26 +1,41 @@
|
||||
'use strict';
|
||||
|
||||
var ELEM_SEP = ':';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.name = 'removeAttrs';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'removes specified attributes';
|
||||
|
||||
exports.params = {
|
||||
attrs: []
|
||||
};
|
||||
const DEFAULT_SEPARATOR = ':';
|
||||
const ENOATTRS = `Warning: The plugin "removeAttrs" requires the "attrs" parameter.
|
||||
It should have a pattern to remove, otherwise the plugin is a noop.
|
||||
Config example:
|
||||
|
||||
plugins: [
|
||||
{
|
||||
name: "removeAttrs",
|
||||
params: {
|
||||
attrs: "(fill|stroke)"
|
||||
}
|
||||
}
|
||||
]
|
||||
`;
|
||||
|
||||
/**
|
||||
* Remove attributes
|
||||
*
|
||||
* @param attrs:
|
||||
* @example elemSeparator
|
||||
* format: string
|
||||
*
|
||||
* format: [ element* : attribute* ]
|
||||
* @example preserveCurrentColor
|
||||
* format: boolean
|
||||
*
|
||||
* element : regexp (wrapped into ^...$), single * or omitted > all elements
|
||||
* @example attrs:
|
||||
*
|
||||
* format: [ element* : attribute* : value* ]
|
||||
*
|
||||
* 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 +48,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,68 +71,89 @@ exports.params = {
|
||||
*
|
||||
* attrs: '.*:(fill|stroke)'
|
||||
*
|
||||
* [is same as]
|
||||
*
|
||||
* attrs: '.*:(fill|stroke):.*'
|
||||
*
|
||||
*
|
||||
* > remove all stroke related attributes
|
||||
* ----
|
||||
* attrs: 'stroke.*'
|
||||
*
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Benny Schudel
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* elemSeparator?: string,
|
||||
* preserveCurrentColor?: boolean,
|
||||
* attrs: string | Array<string>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (root, params) => {
|
||||
if (typeof params.attrs == 'undefined') {
|
||||
console.warn(ENOATTRS);
|
||||
return null;
|
||||
}
|
||||
|
||||
// wrap into an array if params is not
|
||||
if (!Array.isArray(params.attrs)) {
|
||||
params.attrs = [params.attrs];
|
||||
}
|
||||
const elemSeparator =
|
||||
typeof params.elemSeparator == 'string'
|
||||
? params.elemSeparator
|
||||
: DEFAULT_SEPARATOR;
|
||||
const preserveCurrentColor =
|
||||
typeof params.preserveCurrentColor == 'boolean'
|
||||
? params.preserveCurrentColor
|
||||
: false;
|
||||
const attrs = Array.isArray(params.attrs) ? params.attrs : [params.attrs];
|
||||
|
||||
if (item.isElem()) {
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
for (let pattern of attrs) {
|
||||
// if no element separators (:), assume it's attribute name, and apply to all elements *regardless of value*
|
||||
if (pattern.includes(elemSeparator) === false) {
|
||||
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('');
|
||||
}
|
||||
|
||||
// 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('');
|
||||
// create regexps for element, attribute name, and attribute value
|
||||
const list = pattern.split(elemSeparator).map((value) => {
|
||||
// adjust single * to match anything
|
||||
if (value === '*') {
|
||||
value = '.*';
|
||||
}
|
||||
return new RegExp(['^', value, '$'].join(''), 'i');
|
||||
});
|
||||
|
||||
// create regexps for element and attribute name
|
||||
return pattern.split(ELEM_SEP)
|
||||
.map(function(value) {
|
||||
|
||||
// adjust single * to match anything
|
||||
if (value === '*') { value = '.*'; }
|
||||
|
||||
return new RegExp(['^', value, '$'].join(''), 'i');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
// loop patterns
|
||||
patterns.forEach(function(pattern) {
|
||||
|
||||
// matches element
|
||||
if (pattern[0].test(item.elem)) {
|
||||
|
||||
// loop attributes
|
||||
item.eachAttr(function(attr) {
|
||||
var name = attr.name;
|
||||
|
||||
// matches attribute name
|
||||
if (pattern[1].test(name)) {
|
||||
item.removeAttr(name);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// matches element
|
||||
if (list[0].test(node.name)) {
|
||||
// loop attributes
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
const isFillCurrentColor =
|
||||
preserveCurrentColor &&
|
||||
name == 'fill' &&
|
||||
value == 'currentColor';
|
||||
const isStrokeCurrentColor =
|
||||
preserveCurrentColor &&
|
||||
name == 'stroke' &&
|
||||
value == 'currentColor';
|
||||
if (
|
||||
!isFillCurrentColor &&
|
||||
!isStrokeCurrentColor &&
|
||||
// matches attribute name
|
||||
list[1].test(name) &&
|
||||
// matches attribute value
|
||||
list[2].test(value)
|
||||
) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
26
node_modules/svgo/plugins/removeComments.js
generated
vendored
26
node_modules/svgo/plugins/removeComments.js
generated
vendored
@@ -1,9 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeComments';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes comments';
|
||||
|
||||
/**
|
||||
@@ -13,15 +14,18 @@ exports.description = 'removes comments';
|
||||
* <!-- Generator: Adobe Illustrator 15.0.0, SVG Export
|
||||
* Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.comment && item.comment.charAt(0) !== '!') {
|
||||
return false;
|
||||
}
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
comment: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.value.charAt(0) !== '!') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
41
node_modules/svgo/plugins/removeDesc.js
generated
vendored
41
node_modules/svgo/plugins/removeDesc.js
generated
vendored
@@ -1,16 +1,13 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeDesc';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
exports.description = 'removes <desc>';
|
||||
|
||||
exports.params = {
|
||||
removeAny: false
|
||||
};
|
||||
|
||||
exports.description = 'removes <desc> (only non-meaningful by default)';
|
||||
|
||||
var standardDescs = /^Created with/;
|
||||
const standardDescs = /^(Created with|Created using)/;
|
||||
|
||||
/**
|
||||
* Removes <desc>.
|
||||
@@ -19,14 +16,26 @@ var standardDescs = /^Created with/;
|
||||
*
|
||||
* https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Daniel Wabyick
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{ removeAny?: boolean }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
|
||||
return !item.isElem('desc') || !(params.removeAny || item.isEmpty() ||
|
||||
standardDescs.test(item.content[0].text));
|
||||
|
||||
exports.fn = (root, params) => {
|
||||
const { removeAny = true } = params;
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'desc') {
|
||||
if (
|
||||
removeAny ||
|
||||
node.children.length === 0 ||
|
||||
(node.children[0].type === 'text' &&
|
||||
standardDescs.test(node.children[0].value))
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
35
node_modules/svgo/plugins/removeDimensions.js
generated
vendored
35
node_modules/svgo/plugins/removeDimensions.js
generated
vendored
@@ -1,32 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
exports.name = 'removeDimensions';
|
||||
|
||||
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.
|
||||
* Remove width/height attributes and add the viewBox attribute if it's missing
|
||||
*
|
||||
* @example
|
||||
* <svg width="100" height="50" viewBox="0 0 100 50">
|
||||
* <svg width="100" height="50" />
|
||||
* ↓
|
||||
* <svg viewBox="0 0 100 50">
|
||||
* <svg viewBox="0 0 100 50" />
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if true, with and height will be filtered out
|
||||
*
|
||||
* @author Benny Schudel
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (
|
||||
item.isElem('svg') &&
|
||||
item.hasAttr('viewBox')
|
||||
exports.fn = function (item) {
|
||||
if (item.type === 'element' && item.name === 'svg') {
|
||||
if (item.attributes.viewBox != null) {
|
||||
delete item.attributes.width;
|
||||
delete item.attributes.height;
|
||||
} else if (
|
||||
item.attributes.width != null &&
|
||||
item.attributes.height != null &&
|
||||
Number.isNaN(Number(item.attributes.width)) === false &&
|
||||
Number.isNaN(Number(item.attributes.height)) === false
|
||||
) {
|
||||
item.removeAttr('width');
|
||||
item.removeAttr('height');
|
||||
const width = Number(item.attributes.width);
|
||||
const height = Number(item.attributes.height);
|
||||
item.attributes.viewBox = `0 0 ${width} ${height}`;
|
||||
delete item.attributes.width;
|
||||
delete item.attributes.height;
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
24
node_modules/svgo/plugins/removeDoctype.js
generated
vendored
24
node_modules/svgo/plugins/removeDoctype.js
generated
vendored
@@ -1,9 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeDoctype';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes doctype declaration';
|
||||
|
||||
/**
|
||||
@@ -26,15 +27,16 @@ exports.description = 'removes doctype declaration';
|
||||
* <!-- an internal subset can be embedded here -->
|
||||
* ]>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.doctype) {
|
||||
return false;
|
||||
}
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
doctype: {
|
||||
enter: (node, parentNode) => {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
95
node_modules/svgo/plugins/removeEditorsNSData.js
generated
vendored
95
node_modules/svgo/plugins/removeEditorsNSData.js
generated
vendored
@@ -1,18 +1,13 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { editorNamespaces } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeEditorsNSData';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes editors namespaces, elements and attributes';
|
||||
|
||||
var editorNamespaces = require('./_collections').editorNamespaces,
|
||||
prefixes = [];
|
||||
|
||||
exports.params = {
|
||||
additionalNamespaces: []
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove editors namespaces, elements and attributes.
|
||||
*
|
||||
@@ -21,45 +16,53 @@ exports.params = {
|
||||
* <sodipodi:namedview/>
|
||||
* <path sodipodi:nodetypes="cccc"/>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* additionalNamespaces?: Array<string>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
|
||||
if (Array.isArray(params.additionalNamespaces)) {
|
||||
editorNamespaces = editorNamespaces.concat(params.additionalNamespaces);
|
||||
}
|
||||
|
||||
if (item.elem) {
|
||||
|
||||
if (item.isElem('svg')) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
if (attr.prefix === 'xmlns' && editorNamespaces.indexOf(attr.value) > -1) {
|
||||
prefixes.push(attr.local);
|
||||
|
||||
// <svg xmlns:sodipodi="">
|
||||
item.removeAttr(attr.name);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// <* sodipodi:*="">
|
||||
item.eachAttr(function(attr) {
|
||||
if (prefixes.indexOf(attr.prefix) > -1) {
|
||||
item.removeAttr(attr.name);
|
||||
exports.fn = (_root, params) => {
|
||||
let namespaces = editorNamespaces;
|
||||
if (Array.isArray(params.additionalNamespaces)) {
|
||||
namespaces = [...editorNamespaces, ...params.additionalNamespaces];
|
||||
}
|
||||
/**
|
||||
* @type {Array<string>}
|
||||
*/
|
||||
const prefixes = [];
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// collect namespace aliases from svg element
|
||||
if (node.name === 'svg') {
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (name.startsWith('xmlns:') && namespaces.includes(value)) {
|
||||
prefixes.push(name.slice('xmlns:'.length));
|
||||
// <svg xmlns:sodipodi="">
|
||||
delete node.attributes[name];
|
||||
}
|
||||
});
|
||||
|
||||
// <sodipodi:*>
|
||||
if (prefixes.indexOf(item.prefix) > -1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// remove editor attributes, for example
|
||||
// <* sodipodi:*="">
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.includes(':')) {
|
||||
const [prefix] = name.split(':');
|
||||
if (prefixes.includes(prefix)) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
// remove editor elements, for example
|
||||
// <sodipodi:*>
|
||||
if (node.name.includes(':')) {
|
||||
const [prefix] = node.name.split(':');
|
||||
if (prefixes.includes(prefix)) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
78
node_modules/svgo/plugins/removeElementsByAttr.js
generated
vendored
Normal file
78
node_modules/svgo/plugins/removeElementsByAttr.js
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
'use strict';
|
||||
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeElementsByAttr';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
exports.description =
|
||||
'removes arbitrary elements by ID or className (disabled by default)';
|
||||
|
||||
/**
|
||||
* Remove arbitrary SVG elements by ID or className.
|
||||
*
|
||||
* @example id
|
||||
* > single: remove element with ID of `elementID`
|
||||
* ---
|
||||
* removeElementsByAttr:
|
||||
* id: 'elementID'
|
||||
*
|
||||
* > list: remove multiple elements by ID
|
||||
* ---
|
||||
* removeElementsByAttr:
|
||||
* id:
|
||||
* - 'elementID'
|
||||
* - 'anotherID'
|
||||
*
|
||||
* @example class
|
||||
* > single: remove all elements with class of `elementClass`
|
||||
* ---
|
||||
* removeElementsByAttr:
|
||||
* class: 'elementClass'
|
||||
*
|
||||
* > list: remove all elements with class of `elementClass` or `anotherClass`
|
||||
* ---
|
||||
* removeElementsByAttr:
|
||||
* class:
|
||||
* - 'elementClass'
|
||||
* - 'anotherClass'
|
||||
*
|
||||
* @author Eli Dupuis (@elidupuis)
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* id?: string | Array<string>,
|
||||
* class?: string | Array<string>
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = (root, params) => {
|
||||
const ids =
|
||||
params.id == null ? [] : Array.isArray(params.id) ? params.id : [params.id];
|
||||
const classes =
|
||||
params.class == null
|
||||
? []
|
||||
: Array.isArray(params.class)
|
||||
? params.class
|
||||
: [params.class];
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// remove element if it's `id` matches configured `id` params
|
||||
if (node.attributes.id != null && ids.length !== 0) {
|
||||
if (ids.includes(node.attributes.id)) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
}
|
||||
// remove element if it's `class` contains any of the configured `class` params
|
||||
if (node.attributes.class && classes.length !== 0) {
|
||||
const classList = node.attributes.class.split(' ');
|
||||
for (const item of classes) {
|
||||
if (classList.includes(item)) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
38
node_modules/svgo/plugins/removeEmptyAttrs.js
generated
vendored
38
node_modules/svgo/plugins/removeEmptyAttrs.js
generated
vendored
@@ -1,29 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { attrsGroups } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeEmptyAttrs';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes empty attributes';
|
||||
|
||||
/**
|
||||
* Remove attributes with empty values.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.elem) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
if (attr.value === '') {
|
||||
item.removeAttr(attr.name);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (
|
||||
value === '' &&
|
||||
// empty conditional processing attributes prevents elements from rendering
|
||||
attrsGroups.conditionalProcessing.includes(name) === false
|
||||
) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
52
node_modules/svgo/plugins/removeEmptyContainers.js
generated
vendored
52
node_modules/svgo/plugins/removeEmptyContainers.js
generated
vendored
@@ -1,17 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItemReverse';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { elemsGroups } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeEmptyContainers';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes empty container elements';
|
||||
|
||||
var container = require('./_collections').elemsGroups.container;
|
||||
|
||||
/**
|
||||
* Remove empty containers.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/intro.html#TermContainerElement
|
||||
* @see https://www.w3.org/TR/SVG11/intro.html#TermContainerElement
|
||||
*
|
||||
* @example
|
||||
* <defs/>
|
||||
@@ -19,14 +19,40 @@ var container = require('./_collections').elemsGroups.container;
|
||||
* @example
|
||||
* <g><marker><a/></marker></g>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
return !(item.isElem(container) && !item.isElem('svg') && item.isEmpty() &&
|
||||
(!item.isElem('pattern') || !item.hasAttrLocal('href')));
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
exit: (node, parentNode) => {
|
||||
// remove only empty non-svg containers
|
||||
if (
|
||||
node.name === 'svg' ||
|
||||
elemsGroups.container.includes(node.name) === false ||
|
||||
node.children.length !== 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// empty patterns may contain reusable configuration
|
||||
if (
|
||||
node.name === 'pattern' &&
|
||||
Object.keys(node.attributes).length !== 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// The <g> may not have content, but the filter may cause a rectangle
|
||||
// to be created and filled with pattern.
|
||||
if (node.name === 'g' && node.attributes.filter != null) {
|
||||
return;
|
||||
}
|
||||
// empty <mask> hides masked element
|
||||
if (node.name === 'mask' && node.attributes.id != null) {
|
||||
return;
|
||||
}
|
||||
detachNodeFromParent(node, parentNode);
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
70
node_modules/svgo/plugins/removeEmptyText.js
generated
vendored
70
node_modules/svgo/plugins/removeEmptyText.js
generated
vendored
@@ -1,21 +1,16 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeEmptyText';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes empty <text> elements';
|
||||
|
||||
exports.params = {
|
||||
text: true,
|
||||
tspan: true,
|
||||
tref: true
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove empty Text elements.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/text.html
|
||||
* @see https://www.w3.org/TR/SVG11/text.html
|
||||
*
|
||||
* @example
|
||||
* Remove empty text element:
|
||||
@@ -27,33 +22,36 @@ exports.params = {
|
||||
* Remove tref with empty xlink:href attribute:
|
||||
* <tref xlink:href=""/>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* text?: boolean,
|
||||
* tspan?: boolean,
|
||||
* tref?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
|
||||
// Remove empty text element
|
||||
if (
|
||||
params.text &&
|
||||
item.isElem('text') &&
|
||||
item.isEmpty()
|
||||
) return false;
|
||||
|
||||
// Remove empty tspan element
|
||||
if (
|
||||
params.tspan &&
|
||||
item.isElem('tspan') &&
|
||||
item.isEmpty()
|
||||
) return false;
|
||||
|
||||
// Remove tref with empty xlink:href attribute
|
||||
if (
|
||||
params.tref &&
|
||||
item.isElem('tref') &&
|
||||
!item.hasAttrLocal('href')
|
||||
) return false;
|
||||
|
||||
exports.fn = (root, params) => {
|
||||
const { text = true, tspan = true, tref = true } = params;
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// Remove empty text element
|
||||
if (text && node.name === 'text' && node.children.length === 0) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
// Remove empty tspan element
|
||||
if (tspan && node.name === 'tspan' && node.children.length === 0) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
// Remove tref with empty xlink:href attribute
|
||||
if (
|
||||
tref &&
|
||||
node.name === 'tref' &&
|
||||
node.attributes['xlink:href'] == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
312
node_modules/svgo/plugins/removeHiddenElems.js
generated
vendored
312
node_modules/svgo/plugins/removeHiddenElems.js
generated
vendored
@@ -1,29 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const {
|
||||
querySelector,
|
||||
closestByName,
|
||||
detachNodeFromParent,
|
||||
} = require('../lib/xast.js');
|
||||
const { collectStylesheet, computeStyle } = require('../lib/style.js');
|
||||
const { parsePathData } = require('../lib/path.js');
|
||||
|
||||
exports.name = 'removeHiddenElems';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes hidden elements (zero sized, with absent attributes)';
|
||||
|
||||
exports.params = {
|
||||
displayNone: true,
|
||||
opacity0: true,
|
||||
circleR0: true,
|
||||
ellipseRX0: true,
|
||||
ellipseRY0: true,
|
||||
rectWidth0: true,
|
||||
rectHeight0: true,
|
||||
patternWidth0: true,
|
||||
patternHeight0: true,
|
||||
imageWidth0: true,
|
||||
imageHeight0: true,
|
||||
pathEmptyD: true,
|
||||
polylineEmptyPoints: true,
|
||||
polygonEmptyPoints: true
|
||||
};
|
||||
|
||||
var regValidPath = /M\s*(?:[-+]?(?:\d*\.\d+|\d+(?:\.|(?!\.)))([eE][-+]?\d+)?(?!\d)\s*,?\s*){2}\D*\d/i;
|
||||
exports.description =
|
||||
'removes hidden elements (zero sized, with absent attributes)';
|
||||
|
||||
/**
|
||||
* Remove hidden elements with disabled rendering:
|
||||
@@ -38,181 +27,292 @@ var regValidPath = /M\s*(?:[-+]?(?:\d*\.\d+|\d+(?:\.|(?!\.)))([eE][-+]?\d+)?(?!\
|
||||
* - polyline with empty points
|
||||
* - polygon with empty points
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* isHidden: boolean,
|
||||
* displayNone: boolean,
|
||||
* opacity0: boolean,
|
||||
* circleR0: boolean,
|
||||
* ellipseRX0: boolean,
|
||||
* ellipseRY0: boolean,
|
||||
* rectWidth0: boolean,
|
||||
* rectHeight0: boolean,
|
||||
* patternWidth0: boolean,
|
||||
* patternHeight0: boolean,
|
||||
* imageWidth0: boolean,
|
||||
* imageHeight0: boolean,
|
||||
* pathEmptyD: boolean,
|
||||
* polylineEmptyPoints: boolean,
|
||||
* polygonEmptyPoints: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (root, params) => {
|
||||
const {
|
||||
isHidden = true,
|
||||
displayNone = true,
|
||||
opacity0 = true,
|
||||
circleR0 = true,
|
||||
ellipseRX0 = true,
|
||||
ellipseRY0 = true,
|
||||
rectWidth0 = true,
|
||||
rectHeight0 = true,
|
||||
patternWidth0 = true,
|
||||
patternHeight0 = true,
|
||||
imageWidth0 = true,
|
||||
imageHeight0 = true,
|
||||
pathEmptyD = true,
|
||||
polylineEmptyPoints = true,
|
||||
polygonEmptyPoints = true,
|
||||
} = params;
|
||||
const stylesheet = collectStylesheet(root);
|
||||
|
||||
if (item.elem) {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// Removes hidden elements
|
||||
// https://www.w3schools.com/cssref/pr_class_visibility.asp
|
||||
const computedStyle = computeStyle(stylesheet, node);
|
||||
if (
|
||||
isHidden &&
|
||||
computedStyle.visibility &&
|
||||
computedStyle.visibility.type === 'static' &&
|
||||
computedStyle.visibility.value === 'hidden' &&
|
||||
// keep if any descendant enables visibility
|
||||
querySelector(node, '[visibility=visible]') == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// display="none"
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/painting.html#DisplayProperty
|
||||
// https://www.w3.org/TR/SVG11/painting.html#DisplayProperty
|
||||
// "A value of display: none indicates that the given element
|
||||
// and its children shall not be rendered directly"
|
||||
if (
|
||||
params.displayNone &&
|
||||
item.hasAttr('display', 'none')
|
||||
) return false;
|
||||
displayNone &&
|
||||
computedStyle.display &&
|
||||
computedStyle.display.type === 'static' &&
|
||||
computedStyle.display.value === 'none' &&
|
||||
// markers with display: none still rendered
|
||||
node.name !== 'marker'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// opacity="0"
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/masking.html#ObjectAndGroupOpacityProperties
|
||||
// https://www.w3.org/TR/SVG11/masking.html#ObjectAndGroupOpacityProperties
|
||||
if (
|
||||
params.opacity0 &&
|
||||
item.hasAttr('opacity', '0')
|
||||
) return false;
|
||||
opacity0 &&
|
||||
computedStyle.opacity &&
|
||||
computedStyle.opacity.type === 'static' &&
|
||||
computedStyle.opacity.value === '0' &&
|
||||
// transparent element inside clipPath still affect clipped elements
|
||||
closestByName(node, 'clipPath') == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Circles with zero radius
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#CircleElementRAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#CircleElementRAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <circle r="0">
|
||||
if (
|
||||
params.circleR0 &&
|
||||
item.isElem('circle') &&
|
||||
item.isEmpty() &&
|
||||
item.hasAttr('r', '0')
|
||||
) return false;
|
||||
circleR0 &&
|
||||
node.name === 'circle' &&
|
||||
node.children.length === 0 &&
|
||||
node.attributes.r === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ellipse with zero x-axis radius
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#EllipseElementRXAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#EllipseElementRXAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <ellipse rx="0">
|
||||
if (
|
||||
params.ellipseRX0 &&
|
||||
item.isElem('ellipse') &&
|
||||
item.isEmpty() &&
|
||||
item.hasAttr('rx', '0')
|
||||
) return false;
|
||||
ellipseRX0 &&
|
||||
node.name === 'ellipse' &&
|
||||
node.children.length === 0 &&
|
||||
node.attributes.rx === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ellipse with zero y-axis radius
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#EllipseElementRYAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#EllipseElementRYAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <ellipse ry="0">
|
||||
if (
|
||||
params.ellipseRY0 &&
|
||||
item.isElem('ellipse') &&
|
||||
item.isEmpty() &&
|
||||
item.hasAttr('ry', '0')
|
||||
) return false;
|
||||
ellipseRY0 &&
|
||||
node.name === 'ellipse' &&
|
||||
node.children.length === 0 &&
|
||||
node.attributes.ry === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Rectangle with zero width
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#RectElementWidthAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#RectElementWidthAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <rect width="0">
|
||||
if (
|
||||
params.rectWidth0 &&
|
||||
item.isElem('rect') &&
|
||||
item.isEmpty() &&
|
||||
item.hasAttr('width', '0')
|
||||
) return false;
|
||||
rectWidth0 &&
|
||||
node.name === 'rect' &&
|
||||
node.children.length === 0 &&
|
||||
node.attributes.width === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Rectangle with zero height
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#RectElementHeightAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#RectElementHeightAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <rect height="0">
|
||||
if (
|
||||
params.rectHeight0 &&
|
||||
params.rectWidth0 &&
|
||||
item.isElem('rect') &&
|
||||
item.isEmpty() &&
|
||||
item.hasAttr('height', '0')
|
||||
) return false;
|
||||
rectHeight0 &&
|
||||
rectWidth0 &&
|
||||
node.name === 'rect' &&
|
||||
node.children.length === 0 &&
|
||||
node.attributes.height === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pattern with zero width
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/pservers.html#PatternElementWidthAttribute
|
||||
// https://www.w3.org/TR/SVG11/pservers.html#PatternElementWidthAttribute
|
||||
// "A value of zero disables rendering of the element (i.e., no paint is applied)"
|
||||
//
|
||||
// <pattern width="0">
|
||||
if (
|
||||
params.patternWidth0 &&
|
||||
item.isElem('pattern') &&
|
||||
item.hasAttr('width', '0')
|
||||
) return false;
|
||||
patternWidth0 &&
|
||||
node.name === 'pattern' &&
|
||||
node.attributes.width === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Pattern with zero height
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/pservers.html#PatternElementHeightAttribute
|
||||
// https://www.w3.org/TR/SVG11/pservers.html#PatternElementHeightAttribute
|
||||
// "A value of zero disables rendering of the element (i.e., no paint is applied)"
|
||||
//
|
||||
// <pattern height="0">
|
||||
if (
|
||||
params.patternHeight0 &&
|
||||
item.isElem('pattern') &&
|
||||
item.hasAttr('height', '0')
|
||||
) return false;
|
||||
patternHeight0 &&
|
||||
node.name === 'pattern' &&
|
||||
node.attributes.height === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Image with zero width
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/struct.html#ImageElementWidthAttribute
|
||||
// https://www.w3.org/TR/SVG11/struct.html#ImageElementWidthAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <image width="0">
|
||||
if (
|
||||
params.imageWidth0 &&
|
||||
item.isElem('image') &&
|
||||
item.hasAttr('width', '0')
|
||||
) return false;
|
||||
imageWidth0 &&
|
||||
node.name === 'image' &&
|
||||
node.attributes.width === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Image with zero height
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/struct.html#ImageElementHeightAttribute
|
||||
// https://www.w3.org/TR/SVG11/struct.html#ImageElementHeightAttribute
|
||||
// "A value of zero disables rendering of the element"
|
||||
//
|
||||
// <image height="0">
|
||||
if (
|
||||
params.imageHeight0 &&
|
||||
item.isElem('image') &&
|
||||
item.hasAttr('height', '0')
|
||||
) return false;
|
||||
imageHeight0 &&
|
||||
node.name === 'image' &&
|
||||
node.attributes.height === '0'
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Path with empty data
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/paths.html#DAttribute
|
||||
// https://www.w3.org/TR/SVG11/paths.html#DAttribute
|
||||
//
|
||||
// <path d=""/>
|
||||
if (
|
||||
params.pathEmptyD &&
|
||||
item.isElem('path') &&
|
||||
(!item.hasAttr('d') || !regValidPath.test(item.attr('d').value))
|
||||
) return false;
|
||||
if (pathEmptyD && node.name === 'path') {
|
||||
if (node.attributes.d == null) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
const pathData = parsePathData(node.attributes.d);
|
||||
if (pathData.length === 0) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
// keep single point paths for markers
|
||||
if (
|
||||
pathData.length === 1 &&
|
||||
computedStyle['marker-start'] == null &&
|
||||
computedStyle['marker-end'] == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Polyline with empty points
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#PolylineElementPointsAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#PolylineElementPointsAttribute
|
||||
//
|
||||
// <polyline points="">
|
||||
if (
|
||||
params.polylineEmptyPoints &&
|
||||
item.isElem('polyline') &&
|
||||
!item.hasAttr('points')
|
||||
) return false;
|
||||
polylineEmptyPoints &&
|
||||
node.name === 'polyline' &&
|
||||
node.attributes.points == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
|
||||
// Polygon with empty points
|
||||
//
|
||||
// http://www.w3.org/TR/SVG/shapes.html#PolygonElementPointsAttribute
|
||||
// https://www.w3.org/TR/SVG11/shapes.html#PolygonElementPointsAttribute
|
||||
//
|
||||
// <polygon points="">
|
||||
if (
|
||||
params.polygonEmptyPoints &&
|
||||
item.isElem('polygon') &&
|
||||
!item.hasAttr('points')
|
||||
) return false;
|
||||
|
||||
}
|
||||
|
||||
polygonEmptyPoints &&
|
||||
node.name === 'polygon' &&
|
||||
node.attributes.points == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
26
node_modules/svgo/plugins/removeMetadata.js
generated
vendored
26
node_modules/svgo/plugins/removeMetadata.js
generated
vendored
@@ -1,23 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeMetadata';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes <metadata>';
|
||||
|
||||
/**
|
||||
* Remove <metadata>.
|
||||
*
|
||||
* http://www.w3.org/TR/SVG/metadata.html
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
* https://www.w3.org/TR/SVG11/metadata.html
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
return !item.isElem('metadata');
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'metadata') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
42
node_modules/svgo/plugins/removeNonInheritableGroupAttrs.js
generated
vendored
42
node_modules/svgo/plugins/removeNonInheritableGroupAttrs.js
generated
vendored
@@ -1,14 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
exports.name = 'removeNonInheritableGroupAttrs';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes non-inheritable group’s presentational attributes';
|
||||
exports.description =
|
||||
'removes non-inheritable group’s presentational attributes';
|
||||
|
||||
var inheritableAttrs = require('./_collections').inheritableAttrs,
|
||||
attrsGroups = require('./_collections').attrsGroups,
|
||||
excludedAttrs = ['display', 'opacity'];
|
||||
const {
|
||||
inheritableAttrs,
|
||||
attrsGroups,
|
||||
presentationNonInheritableGroupAttrs,
|
||||
} = require('./_collections');
|
||||
|
||||
/**
|
||||
* Remove non-inheritable group's "presentation" attributes.
|
||||
@@ -18,23 +23,16 @@ var inheritableAttrs = require('./_collections').inheritableAttrs,
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.isElem('g')) {
|
||||
|
||||
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)
|
||||
) {
|
||||
item.removeAttr(attr.name);
|
||||
}
|
||||
});
|
||||
|
||||
exports.fn = function (item) {
|
||||
if (item.type === 'element' && item.name === 'g') {
|
||||
for (const name of Object.keys(item.attributes)) {
|
||||
if (
|
||||
attrsGroups.presentation.includes(name) === true &&
|
||||
inheritableAttrs.includes(name) === false &&
|
||||
presentationNonInheritableGroupAttrs.includes(name) === false
|
||||
) {
|
||||
delete item.attributes[name];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
138
node_modules/svgo/plugins/removeOffCanvasPaths.js
generated
vendored
Normal file
138
node_modules/svgo/plugins/removeOffCanvasPaths.js
generated
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('../lib/types').PathDataItem} PathDataItem
|
||||
*/
|
||||
|
||||
const { visitSkip, detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { parsePathData } = require('../lib/path.js');
|
||||
const { intersects } = require('./_path.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeOffCanvasPaths';
|
||||
exports.active = false;
|
||||
exports.description =
|
||||
'removes elements that are drawn outside of the viewbox (disabled by default)';
|
||||
|
||||
/**
|
||||
* Remove elements that are drawn outside of the viewbox.
|
||||
*
|
||||
* @author JoshyPHP
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = () => {
|
||||
/**
|
||||
* @type {null | {
|
||||
* top: number,
|
||||
* right: number,
|
||||
* bottom: number,
|
||||
* left: number,
|
||||
* width: number,
|
||||
* height: number
|
||||
* }}
|
||||
*/
|
||||
let viewBoxData = null;
|
||||
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
let viewBox = '';
|
||||
// find viewbox
|
||||
if (node.attributes.viewBox != null) {
|
||||
// remove commas and plus signs, normalize and trim whitespace
|
||||
viewBox = node.attributes.viewBox;
|
||||
} else if (
|
||||
node.attributes.height != null &&
|
||||
node.attributes.width != null
|
||||
) {
|
||||
viewBox = `0 0 ${node.attributes.width} ${node.attributes.height}`;
|
||||
}
|
||||
|
||||
// parse viewbox
|
||||
// remove commas and plus signs, normalize and trim whitespace
|
||||
viewBox = viewBox
|
||||
.replace(/[,+]|px/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/^\s*|\s*$/g, '');
|
||||
// ensure that the dimensions are 4 values separated by space
|
||||
const m =
|
||||
/^(-?\d*\.?\d+) (-?\d*\.?\d+) (\d*\.?\d+) (\d*\.?\d+)$/.exec(
|
||||
viewBox
|
||||
);
|
||||
if (m == null) {
|
||||
return;
|
||||
}
|
||||
const left = Number.parseFloat(m[1]);
|
||||
const top = Number.parseFloat(m[2]);
|
||||
const width = Number.parseFloat(m[3]);
|
||||
const height = Number.parseFloat(m[4]);
|
||||
|
||||
// store the viewBox boundaries
|
||||
viewBoxData = {
|
||||
left,
|
||||
top,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
// consider that any item with a transform attribute is visible
|
||||
if (node.attributes.transform != null) {
|
||||
return visitSkip;
|
||||
}
|
||||
|
||||
if (
|
||||
node.name === 'path' &&
|
||||
node.attributes.d != null &&
|
||||
viewBoxData != null
|
||||
) {
|
||||
const pathData = parsePathData(node.attributes.d);
|
||||
|
||||
// consider that a M command within the viewBox is visible
|
||||
let visible = false;
|
||||
for (const pathDataItem of pathData) {
|
||||
if (pathDataItem.command === 'M') {
|
||||
const [x, y] = pathDataItem.args;
|
||||
if (
|
||||
x >= viewBoxData.left &&
|
||||
x <= viewBoxData.right &&
|
||||
y >= viewBoxData.top &&
|
||||
y <= viewBoxData.bottom
|
||||
) {
|
||||
visible = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathData.length === 2) {
|
||||
// close the path too short for intersects()
|
||||
pathData.push({ command: 'z', args: [] });
|
||||
}
|
||||
|
||||
const { left, top, width, height } = viewBoxData;
|
||||
/**
|
||||
* @type {Array<PathDataItem>}
|
||||
*/
|
||||
const viewBoxPathData = [
|
||||
{ command: 'M', args: [left, top] },
|
||||
{ command: 'h', args: [width] },
|
||||
{ command: 'v', args: [height] },
|
||||
{ command: 'H', args: [left] },
|
||||
{ command: 'z', args: [] },
|
||||
];
|
||||
|
||||
if (intersects(viewBoxPathData, pathData) === false) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
33
node_modules/svgo/plugins/removeRasterImages.js
generated
vendored
33
node_modules/svgo/plugins/removeRasterImages.js
generated
vendored
@@ -1,9 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeRasterImages';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'removes raster images (disabled by default)';
|
||||
|
||||
/**
|
||||
@@ -11,18 +12,22 @@ exports.description = 'removes raster images (disabled by default)';
|
||||
*
|
||||
* @see https://bugs.webkit.org/show_bug.cgi?id=63548
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (
|
||||
item.isElem('image') &&
|
||||
item.hasAttrLocal('href', /(\.|image\/)(jpg|png|gif)/)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (
|
||||
node.name === 'image' &&
|
||||
node.attributes['xlink:href'] != null &&
|
||||
/(\.|image\/)(jpg|png|gif)/.test(node.attributes['xlink:href'])
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
29
node_modules/svgo/plugins/removeScriptElement.js
generated
vendored
Normal file
29
node_modules/svgo/plugins/removeScriptElement.js
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeScriptElement';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
exports.description = 'removes <script> elements (disabled by default)';
|
||||
|
||||
/**
|
||||
* Remove <script>.
|
||||
*
|
||||
* https://www.w3.org/TR/SVG11/script.html
|
||||
*
|
||||
* @author Patrick Klingemann
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'script') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
26
node_modules/svgo/plugins/removeStyleElement.js
generated
vendored
26
node_modules/svgo/plugins/removeStyleElement.js
generated
vendored
@@ -1,23 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeStyleElement';
|
||||
exports.type = 'visitor';
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'removes <style> element (disabled by default)';
|
||||
|
||||
/**
|
||||
* Remove <style>.
|
||||
*
|
||||
* http://www.w3.org/TR/SVG/styling.html#StyleElement
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
* https://www.w3.org/TR/SVG11/styling.html#StyleElement
|
||||
*
|
||||
* @author Betsy Dupuis
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
return !item.isElem('style');
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'style') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
29
node_modules/svgo/plugins/removeTitle.js
generated
vendored
29
node_modules/svgo/plugins/removeTitle.js
generated
vendored
@@ -1,24 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'removes <title> (disabled by default)';
|
||||
exports.name = 'removeTitle';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
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
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Igor Kalashnikov
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
return !item.isElem('title');
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'title') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
308
node_modules/svgo/plugins/removeUnknownsAndDefaults.js
generated
vendored
308
node_modules/svgo/plugins/removeUnknownsAndDefaults.js
generated
vendored
@@ -1,142 +1,218 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { visitSkip, detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { collectStylesheet, computeStyle } = require('../lib/style.js');
|
||||
const {
|
||||
elems,
|
||||
attrsGroups,
|
||||
elemsGroups,
|
||||
attrsGroupsDefaults,
|
||||
presentationNonInheritableGroupAttrs,
|
||||
} = require('./_collections');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeUnknownsAndDefaults';
|
||||
exports.active = true;
|
||||
exports.description =
|
||||
'removes unknown elements content and attributes, removes attrs with default values';
|
||||
|
||||
exports.description = 'removes unknown elements content and attributes, removes attrs with default values';
|
||||
// resolve all groups references
|
||||
|
||||
exports.params = {
|
||||
unknownContent: true,
|
||||
unknownAttrs: true,
|
||||
defaultAttrs: true,
|
||||
uselessOverrides: true,
|
||||
keepDataAttrs: true
|
||||
};
|
||||
|
||||
var collections = require('./_collections'),
|
||||
elems = collections.elems,
|
||||
attrsGroups = collections.attrsGroups,
|
||||
elemsGroups = collections.elemsGroups,
|
||||
attrsGroupsDefaults = collections.attrsGroupsDefaults,
|
||||
attrsInheritable = collections.inheritableAttrs;
|
||||
|
||||
// collect and extend all references
|
||||
for (var elem in elems) {
|
||||
elem = elems[elem];
|
||||
|
||||
if (elem.attrsGroups) {
|
||||
elem.attrs = elem.attrs || [];
|
||||
|
||||
elem.attrsGroups.forEach(function(attrsGroupName) {
|
||||
elem.attrs = elem.attrs.concat(attrsGroups[attrsGroupName]);
|
||||
|
||||
var groupDefaults = attrsGroupsDefaults[attrsGroupName];
|
||||
|
||||
if (groupDefaults) {
|
||||
elem.defaults = elem.defaults || {};
|
||||
|
||||
for (var attrName in groupDefaults) {
|
||||
elem.defaults[attrName] = groupDefaults[attrName];
|
||||
}
|
||||
}
|
||||
});
|
||||
/**
|
||||
* @type {Map<string, Set<string>>}
|
||||
*/
|
||||
const allowedChildrenPerElement = new Map();
|
||||
/**
|
||||
* @type {Map<string, Set<string>>}
|
||||
*/
|
||||
const allowedAttributesPerElement = new Map();
|
||||
/**
|
||||
* @type {Map<string, Map<string, string>>}
|
||||
*/
|
||||
const attributesDefaultsPerElement = new Map();
|
||||
|
||||
for (const [name, config] of Object.entries(elems)) {
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const allowedChildren = new Set();
|
||||
if (config.content) {
|
||||
for (const elementName of config.content) {
|
||||
allowedChildren.add(elementName);
|
||||
}
|
||||
|
||||
if (elem.contentGroups) {
|
||||
elem.content = elem.content || [];
|
||||
|
||||
elem.contentGroups.forEach(function(contentGroupName) {
|
||||
elem.content = elem.content.concat(elemsGroups[contentGroupName]);
|
||||
});
|
||||
}
|
||||
if (config.contentGroups) {
|
||||
for (const contentGroupName of config.contentGroups) {
|
||||
const elemsGroup = elemsGroups[contentGroupName];
|
||||
if (elemsGroup) {
|
||||
for (const elementName of elemsGroup) {
|
||||
allowedChildren.add(elementName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const allowedAttributes = new Set();
|
||||
if (config.attrs) {
|
||||
for (const attrName of config.attrs) {
|
||||
allowedAttributes.add(attrName);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @type {Map<string, string>}
|
||||
*/
|
||||
const attributesDefaults = new Map();
|
||||
if (config.defaults) {
|
||||
for (const [attrName, defaultValue] of Object.entries(config.defaults)) {
|
||||
attributesDefaults.set(attrName, defaultValue);
|
||||
}
|
||||
}
|
||||
for (const attrsGroupName of config.attrsGroups) {
|
||||
const attrsGroup = attrsGroups[attrsGroupName];
|
||||
if (attrsGroup) {
|
||||
for (const attrName of attrsGroup) {
|
||||
allowedAttributes.add(attrName);
|
||||
}
|
||||
}
|
||||
const groupDefaults = attrsGroupsDefaults[attrsGroupName];
|
||||
if (groupDefaults) {
|
||||
for (const [attrName, defaultValue] of Object.entries(groupDefaults)) {
|
||||
attributesDefaults.set(attrName, defaultValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
allowedChildrenPerElement.set(name, allowedChildren);
|
||||
allowedAttributesPerElement.set(name, allowedAttributes);
|
||||
attributesDefaultsPerElement.set(name, attributesDefaults);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove unknown elements content and attributes,
|
||||
* remove attributes with default values.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* unknownContent?: boolean,
|
||||
* unknownAttrs?: boolean,
|
||||
* defaultAttrs?: boolean,
|
||||
* uselessOverrides?: boolean,
|
||||
* keepDataAttrs?: boolean,
|
||||
* keepAriaAttrs?: boolean,
|
||||
* keepRoleAttr?: boolean,
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (root, params) => {
|
||||
const {
|
||||
unknownContent = true,
|
||||
unknownAttrs = true,
|
||||
defaultAttrs = true,
|
||||
uselessOverrides = true,
|
||||
keepDataAttrs = true,
|
||||
keepAriaAttrs = true,
|
||||
keepRoleAttr = false,
|
||||
} = params;
|
||||
const stylesheet = collectStylesheet(root);
|
||||
|
||||
// elems w/o namespace prefix
|
||||
if (item.isElem() && !item.prefix) {
|
||||
|
||||
var elem = item.elem;
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// skip namespaced elements
|
||||
if (node.name.includes(':')) {
|
||||
return;
|
||||
}
|
||||
// skip visiting foreignObject subtree
|
||||
if (node.name === 'foreignObject') {
|
||||
return visitSkip;
|
||||
}
|
||||
|
||||
// remove unknown element's content
|
||||
if (
|
||||
params.unknownContent &&
|
||||
!item.isEmpty() &&
|
||||
elems[elem] && // make sure we know of this element before checking its children
|
||||
elem !== 'foreignObject' // Don't check foreignObject
|
||||
) {
|
||||
item.content.forEach(function(content, i) {
|
||||
if (
|
||||
content.isElem() &&
|
||||
!content.prefix &&
|
||||
(
|
||||
(
|
||||
elems[elem].content && // Do we have a record of its permitted content?
|
||||
elems[elem].content.indexOf(content.elem) === -1
|
||||
) ||
|
||||
(
|
||||
!elems[elem].content && // we dont know about its permitted content
|
||||
!elems[content.elem] // check that we know about the element at all
|
||||
)
|
||||
)
|
||||
) {
|
||||
item.content.splice(i, 1);
|
||||
}
|
||||
});
|
||||
if (unknownContent && parentNode.type === 'element') {
|
||||
const allowedChildren = allowedChildrenPerElement.get(
|
||||
parentNode.name
|
||||
);
|
||||
if (allowedChildren == null || allowedChildren.size === 0) {
|
||||
// remove unknown elements
|
||||
if (allowedChildrenPerElement.get(node.name) == null) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// remove not allowed children
|
||||
if (allowedChildren.has(node.name) === false) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allowedAttributes = allowedAttributesPerElement.get(node.name);
|
||||
const attributesDefaults = attributesDefaultsPerElement.get(node.name);
|
||||
const computedParentStyle =
|
||||
parentNode.type === 'element'
|
||||
? computeStyle(stylesheet, parentNode)
|
||||
: null;
|
||||
|
||||
// remove element's unknown attrs and attrs with default values
|
||||
if (elems[elem] && elems[elem].attrs) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
|
||||
if (
|
||||
attr.name !== 'xmlns' &&
|
||||
(attr.prefix === 'xml' || !attr.prefix) &&
|
||||
(!params.keepDataAttrs || attr.name.indexOf('data-') != 0)
|
||||
) {
|
||||
if (
|
||||
// unknown attrs
|
||||
(
|
||||
params.unknownAttrs &&
|
||||
elems[elem].attrs.indexOf(attr.name) === -1
|
||||
) ||
|
||||
// attrs with default values
|
||||
(
|
||||
params.defaultAttrs &&
|
||||
elems[elem].defaults &&
|
||||
elems[elem].defaults[attr.name] === attr.value && (
|
||||
attrsInheritable.indexOf(attr.name) < 0 ||
|
||||
!item.parentNode.computedAttr(attr.name)
|
||||
)
|
||||
) ||
|
||||
// useless overrides
|
||||
(
|
||||
params.uselessOverrides &&
|
||||
attrsInheritable.indexOf(attr.name) > -1 &&
|
||||
item.parentNode.computedAttr(attr.name, attr.value)
|
||||
)
|
||||
) {
|
||||
item.removeAttr(attr.name);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
for (const [name, value] of Object.entries(node.attributes)) {
|
||||
if (keepDataAttrs && name.startsWith('data-')) {
|
||||
continue;
|
||||
}
|
||||
if (keepAriaAttrs && name.startsWith('aria-')) {
|
||||
continue;
|
||||
}
|
||||
if (keepRoleAttr && name === 'role') {
|
||||
continue;
|
||||
}
|
||||
// skip xmlns attribute
|
||||
if (name === 'xmlns') {
|
||||
continue;
|
||||
}
|
||||
// skip namespaced attributes except xml:* and xlink:*
|
||||
if (name.includes(':')) {
|
||||
const [prefix] = name.split(':');
|
||||
if (prefix !== 'xml' && prefix !== 'xlink') {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
unknownAttrs &&
|
||||
allowedAttributes &&
|
||||
allowedAttributes.has(name) === false
|
||||
) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
if (
|
||||
defaultAttrs &&
|
||||
node.attributes.id == null &&
|
||||
attributesDefaults &&
|
||||
attributesDefaults.get(name) === value
|
||||
) {
|
||||
// keep defaults if parent has own or inherited style
|
||||
if (
|
||||
computedParentStyle == null ||
|
||||
computedParentStyle[name] == null
|
||||
) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
if (uselessOverrides && node.attributes.id == null) {
|
||||
const style =
|
||||
computedParentStyle == null ? null : computedParentStyle[name];
|
||||
if (
|
||||
presentationNonInheritableGroupAttrs.includes(name) === false &&
|
||||
style != null &&
|
||||
style.type === 'static' &&
|
||||
style.value === value
|
||||
) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
144
node_modules/svgo/plugins/removeUnusedNS.js
generated
vendored
144
node_modules/svgo/plugins/removeUnusedNS.js
generated
vendored
@@ -1,107 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'full';
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeUnusedNS';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes unused namespaces declaration';
|
||||
|
||||
/**
|
||||
* Remove unused namespaces declaration.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
* Remove unused namespaces declaration from svg element
|
||||
* which are not used in elements or attributes
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(data) {
|
||||
|
||||
var svgElem,
|
||||
xmlnsCollection = [];
|
||||
|
||||
/**
|
||||
* Remove namespace from collection.
|
||||
*
|
||||
* @param {String} ns namescape name
|
||||
*/
|
||||
function removeNSfromCollection(ns) {
|
||||
|
||||
var pos = xmlnsCollection.indexOf(ns);
|
||||
|
||||
// if found - remove ns from the namespaces collection
|
||||
if (pos > -1) {
|
||||
xmlnsCollection.splice(pos, 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Bananas!
|
||||
*
|
||||
* @param {Array} items input items
|
||||
*
|
||||
* @return {Array} output items
|
||||
*/
|
||||
function monkeys(items) {
|
||||
|
||||
var i = 0,
|
||||
length = items.content.length;
|
||||
|
||||
while(i < length) {
|
||||
|
||||
var item = items.content[i];
|
||||
|
||||
if (item.isElem('svg')) {
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
// collect namespaces
|
||||
if (attr.prefix === 'xmlns' && attr.local) {
|
||||
xmlnsCollection.push(attr.local);
|
||||
}
|
||||
});
|
||||
|
||||
// if svg element has ns-attr
|
||||
if (xmlnsCollection.length) {
|
||||
// save svg element
|
||||
svgElem = item;
|
||||
}
|
||||
|
||||
} else if (xmlnsCollection.length) {
|
||||
|
||||
// check item for the ns-attrs
|
||||
if (item.prefix) {
|
||||
removeNSfromCollection(item.prefix);
|
||||
}
|
||||
|
||||
// check each attr for the ns-attrs
|
||||
item.eachAttr(function(attr) {
|
||||
removeNSfromCollection(attr.prefix);
|
||||
});
|
||||
|
||||
exports.fn = () => {
|
||||
/**
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
const unusedNamespaces = new Set();
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// collect all namespaces from svg element
|
||||
// (such as xmlns:xlink="http://www.w3.org/1999/xlink")
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.startsWith('xmlns:')) {
|
||||
const local = name.slice('xmlns:'.length);
|
||||
unusedNamespaces.add(local);
|
||||
}
|
||||
|
||||
// if nothing is found - go deeper
|
||||
if (xmlnsCollection.length && item.content) {
|
||||
monkeys(item);
|
||||
}
|
||||
|
||||
i++;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
|
||||
}
|
||||
|
||||
data = monkeys(data);
|
||||
|
||||
// remove svg element ns-attributes if they are not used even once
|
||||
if (xmlnsCollection.length) {
|
||||
xmlnsCollection.forEach(function(name) {
|
||||
svgElem.removeAttr('xmlns:' + name);
|
||||
});
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
if (unusedNamespaces.size !== 0) {
|
||||
// preserve namespace used in nested elements names
|
||||
if (node.name.includes(':')) {
|
||||
const [ns] = node.name.split(':');
|
||||
if (unusedNamespaces.has(ns)) {
|
||||
unusedNamespaces.delete(ns);
|
||||
}
|
||||
}
|
||||
// preserve namespace used in nested elements attributes
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.includes(':')) {
|
||||
const [ns] = name.split(':');
|
||||
unusedNamespaces.delete(ns);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
exit: (node, parentNode) => {
|
||||
// remove unused namespace attributes from svg element
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
for (const name of unusedNamespaces) {
|
||||
delete node.attributes[`xmlns:${name}`];
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
88
node_modules/svgo/plugins/removeUselessDefs.js
generated
vendored
88
node_modules/svgo/plugins/removeUselessDefs.js
generated
vendored
@@ -1,51 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
*/
|
||||
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { elemsGroups } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeUselessDefs';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes elements in <defs> without id';
|
||||
|
||||
var nonRendering = require('./_collections').elemsGroups.nonRendering,
|
||||
defs;
|
||||
|
||||
/**
|
||||
* Removes content of defs and properties that aren't rendered directly without ids.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Lev Solntsev
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (item.isElem('defs')) {
|
||||
|
||||
defs = item;
|
||||
item.content = (item.content || []).reduce(getUsefulItems, []);
|
||||
|
||||
if (item.isEmpty()) return false;
|
||||
|
||||
} else if (item.isElem(nonRendering) && !item.hasAttr('id')) {
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'defs') {
|
||||
/**
|
||||
* @type {Array<XastElement>}
|
||||
*/
|
||||
const usefulNodes = [];
|
||||
collectUsefulNodes(node, usefulNodes);
|
||||
if (usefulNodes.length === 0) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
// TODO remove in SVGO 3
|
||||
for (const usefulNode of usefulNodes) {
|
||||
// @ts-ignore parentNode is legacy
|
||||
usefulNode.parentNode = node;
|
||||
}
|
||||
node.children = usefulNodes;
|
||||
} else if (
|
||||
elemsGroups.nonRendering.includes(node.name) &&
|
||||
node.attributes.id == null
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
function getUsefulItems(usefulItems, item) {
|
||||
|
||||
if (item.hasAttr('id') || item.isElem('style')) {
|
||||
|
||||
usefulItems.push(item);
|
||||
item.parentNode = defs;
|
||||
|
||||
} else if (!item.isEmpty()) {
|
||||
|
||||
item.content.reduce(getUsefulItems, usefulItems);
|
||||
|
||||
/**
|
||||
* @type {(node: XastElement, usefulNodes: Array<XastElement>) => void}
|
||||
*/
|
||||
const collectUsefulNodes = (node, usefulNodes) => {
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'element') {
|
||||
if (child.attributes.id != null || child.name === 'style') {
|
||||
usefulNodes.push(child);
|
||||
} else {
|
||||
collectUsefulNodes(child, usefulNodes);
|
||||
}
|
||||
}
|
||||
|
||||
return usefulItems;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
188
node_modules/svgo/plugins/removeUselessStrokeAndFill.js
generated
vendored
188
node_modules/svgo/plugins/removeUselessStrokeAndFill.js
generated
vendored
@@ -1,92 +1,144 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { visit, visitSkip, detachNodeFromParent } = require('../lib/xast.js');
|
||||
const { collectStylesheet, computeStyle } = require('../lib/style.js');
|
||||
const { elemsGroups } = require('./_collections.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeUselessStrokeAndFill';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes useless stroke and fill attributes';
|
||||
|
||||
exports.params = {
|
||||
stroke: true,
|
||||
fill: true
|
||||
};
|
||||
|
||||
var shape = require('./_collections').elemsGroups.shape,
|
||||
regStrokeProps = /^stroke/,
|
||||
regFillProps = /^fill-/,
|
||||
styleOrScript = ['style', 'script'],
|
||||
hasStyleOrScript = false;
|
||||
|
||||
/**
|
||||
* Remove useless stroke and fill attrs.
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @param {Object} params plugin params
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<{
|
||||
* stroke?: boolean,
|
||||
* fill?: boolean,
|
||||
* removeNone?: boolean
|
||||
* }>}
|
||||
*/
|
||||
exports.fn = function(item, params) {
|
||||
exports.fn = (root, params) => {
|
||||
const {
|
||||
stroke: removeStroke = true,
|
||||
fill: removeFill = true,
|
||||
removeNone = false,
|
||||
} = params;
|
||||
|
||||
if (item.isElem(styleOrScript)) {
|
||||
hasStyleOrScript = true;
|
||||
}
|
||||
// style and script elements deoptimise this plugin
|
||||
let hasStyleOrScript = false;
|
||||
visit(root, {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.name === 'style' || node.name === 'script') {
|
||||
hasStyleOrScript = true;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
if (hasStyleOrScript) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!hasStyleOrScript && item.isElem(shape) && !item.computedAttr('id')) {
|
||||
const stylesheet = collectStylesheet(root);
|
||||
|
||||
var stroke = params.stroke && item.computedAttr('stroke'),
|
||||
fill = params.fill && !item.computedAttr('fill', 'none');
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
// id attribute deoptimise the whole subtree
|
||||
if (node.attributes.id != null) {
|
||||
return visitSkip;
|
||||
}
|
||||
if (elemsGroups.shape.includes(node.name) == false) {
|
||||
return;
|
||||
}
|
||||
const computedStyle = computeStyle(stylesheet, node);
|
||||
const stroke = computedStyle.stroke;
|
||||
const strokeOpacity = computedStyle['stroke-opacity'];
|
||||
const strokeWidth = computedStyle['stroke-width'];
|
||||
const markerEnd = computedStyle['marker-end'];
|
||||
const fill = computedStyle.fill;
|
||||
const fillOpacity = computedStyle['fill-opacity'];
|
||||
const computedParentStyle =
|
||||
parentNode.type === 'element'
|
||||
? computeStyle(stylesheet, parentNode)
|
||||
: null;
|
||||
const parentStroke =
|
||||
computedParentStyle == null ? null : computedParentStyle.stroke;
|
||||
|
||||
// remove stroke*
|
||||
if (
|
||||
params.stroke &&
|
||||
(!stroke ||
|
||||
stroke == 'none' ||
|
||||
item.computedAttr('stroke-opacity', '0') ||
|
||||
item.computedAttr('stroke-width', '0')
|
||||
)
|
||||
) {
|
||||
var parentStroke = item.parentNode.computedAttr('stroke'),
|
||||
declineStroke = parentStroke && parentStroke != 'none';
|
||||
|
||||
item.eachAttr(function(attr) {
|
||||
if (regStrokeProps.test(attr.name)) {
|
||||
item.removeAttr(attr.name);
|
||||
if (removeStroke) {
|
||||
if (
|
||||
stroke == null ||
|
||||
(stroke.type === 'static' && stroke.value == 'none') ||
|
||||
(strokeOpacity != null &&
|
||||
strokeOpacity.type === 'static' &&
|
||||
strokeOpacity.value === '0') ||
|
||||
(strokeWidth != null &&
|
||||
strokeWidth.type === 'static' &&
|
||||
strokeWidth.value === '0')
|
||||
) {
|
||||
// stroke-width may affect the size of marker-end
|
||||
// marker is not visible when stroke-width is 0
|
||||
if (
|
||||
(strokeWidth != null &&
|
||||
strokeWidth.type === 'static' &&
|
||||
strokeWidth.value === '0') ||
|
||||
markerEnd == null
|
||||
) {
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.startsWith('stroke')) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
});
|
||||
|
||||
if (declineStroke) item.addAttr({
|
||||
name: 'stroke',
|
||||
value: 'none',
|
||||
prefix: '',
|
||||
local: 'stroke'
|
||||
});
|
||||
}
|
||||
// set explicit none to not inherit from parent
|
||||
if (
|
||||
parentStroke != null &&
|
||||
parentStroke.type === 'static' &&
|
||||
parentStroke.value !== 'none'
|
||||
) {
|
||||
node.attributes.stroke = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove fill*
|
||||
if (
|
||||
params.fill &&
|
||||
(!fill || item.computedAttr('fill-opacity', '0'))
|
||||
) {
|
||||
item.eachAttr(function(attr) {
|
||||
if (regFillProps.test(attr.name)) {
|
||||
item.removeAttr(attr.name);
|
||||
}
|
||||
});
|
||||
|
||||
if (fill) {
|
||||
if (item.hasAttr('fill'))
|
||||
item.attr('fill').value = 'none';
|
||||
else
|
||||
item.addAttr({
|
||||
name: 'fill',
|
||||
value: 'none',
|
||||
prefix: '',
|
||||
local: 'fill'
|
||||
});
|
||||
if (removeFill) {
|
||||
if (
|
||||
(fill != null && fill.type === 'static' && fill.value === 'none') ||
|
||||
(fillOpacity != null &&
|
||||
fillOpacity.type === 'static' &&
|
||||
fillOpacity.value === '0')
|
||||
) {
|
||||
for (const name of Object.keys(node.attributes)) {
|
||||
if (name.startsWith('fill-')) {
|
||||
delete node.attributes[name];
|
||||
}
|
||||
}
|
||||
if (
|
||||
fill == null ||
|
||||
(fill.type === 'static' && fill.value !== 'none')
|
||||
) {
|
||||
node.attributes.fill = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (removeNone) {
|
||||
if (
|
||||
(stroke == null || node.attributes.stroke === 'none') &&
|
||||
((fill != null &&
|
||||
fill.type === 'static' &&
|
||||
fill.value === 'none') ||
|
||||
node.attributes.fill === 'none')
|
||||
) {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
66
node_modules/svgo/plugins/removeViewBox.js
generated
vendored
66
node_modules/svgo/plugins/removeViewBox.js
generated
vendored
@@ -1,49 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'removeViewBox';
|
||||
exports.active = true;
|
||||
exports.description = 'removes viewBox attribute when possible';
|
||||
|
||||
exports.active = false;
|
||||
|
||||
exports.description = 'removes viewBox attribute when possible (disabled by default)';
|
||||
|
||||
var regViewBox = /^0\s0\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)\s([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)$/,
|
||||
viewBoxElems = ['svg', 'pattern'];
|
||||
const viewBoxElems = ['svg', 'pattern', 'symbol'];
|
||||
|
||||
/**
|
||||
* Remove viewBox attr which coincides with a width/height box.
|
||||
*
|
||||
* @see http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
|
||||
* @see https://www.w3.org/TR/SVG11/coords.html#ViewBoxAttribute
|
||||
*
|
||||
* @example
|
||||
* <svg width="100" height="50" viewBox="0 0 100 50">
|
||||
* ⬇
|
||||
* <svg width="100" height="50">
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
if (
|
||||
item.isElem(viewBoxElems) &&
|
||||
item.hasAttr('viewBox') &&
|
||||
item.hasAttr('width') &&
|
||||
item.hasAttr('height')
|
||||
) {
|
||||
|
||||
var match = item.attr('viewBox').value.match(regViewBox);
|
||||
|
||||
if (match) {
|
||||
if (
|
||||
item.attr('width').value === match[1] &&
|
||||
item.attr('height').value === match[3]
|
||||
) {
|
||||
item.removeAttr('viewBox');
|
||||
}
|
||||
exports.fn = () => {
|
||||
return {
|
||||
element: {
|
||||
enter: (node, parentNode) => {
|
||||
if (
|
||||
viewBoxElems.includes(node.name) &&
|
||||
node.attributes.viewBox != null &&
|
||||
node.attributes.width != null &&
|
||||
node.attributes.height != null
|
||||
) {
|
||||
// TODO remove width/height for such case instead
|
||||
if (node.name === 'svg' && parentNode.type !== 'root') {
|
||||
return;
|
||||
}
|
||||
const nums = node.attributes.viewBox.split(/[ ,]+/g);
|
||||
if (
|
||||
nums[0] === '0' &&
|
||||
nums[1] === '0' &&
|
||||
node.attributes.width.replace(/px$/, '') === nums[2] && // could use parseFloat too
|
||||
node.attributes.height.replace(/px$/, '') === nums[3]
|
||||
) {
|
||||
delete node.attributes.viewBox;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
30
node_modules/svgo/plugins/removeXMLNS.js
generated
vendored
Normal file
30
node_modules/svgo/plugins/removeXMLNS.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
exports.name = 'removeXMLNS';
|
||||
|
||||
exports.type = 'perItem';
|
||||
|
||||
exports.active = false;
|
||||
|
||||
exports.description =
|
||||
'removes xmlns attribute (for inline svg, disabled by default)';
|
||||
|
||||
/**
|
||||
* Remove the xmlns attribute when present.
|
||||
*
|
||||
* @example
|
||||
* <svg viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg">
|
||||
* ↓
|
||||
* <svg viewBox="0 0 100 50">
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if true, xmlns will be filtered out
|
||||
*
|
||||
* @author Ricardo Tomasi
|
||||
*/
|
||||
exports.fn = function (item) {
|
||||
if (item.type === 'element' && item.name === 'svg') {
|
||||
delete item.attributes.xmlns;
|
||||
delete item.attributes['xmlns:xlink'];
|
||||
}
|
||||
};
|
||||
24
node_modules/svgo/plugins/removeXMLProcInst.js
generated
vendored
24
node_modules/svgo/plugins/removeXMLProcInst.js
generated
vendored
@@ -1,9 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
exports.type = 'perItem';
|
||||
const { detachNodeFromParent } = require('../lib/xast.js');
|
||||
|
||||
exports.name = 'removeXMLProcInst';
|
||||
exports.type = 'visitor';
|
||||
exports.active = true;
|
||||
|
||||
exports.description = 'removes XML processing instructions';
|
||||
|
||||
/**
|
||||
@@ -12,13 +13,18 @@ exports.description = 'removes XML processing instructions';
|
||||
* @example
|
||||
* <?xml version="1.0" encoding="utf-8"?>
|
||||
*
|
||||
* @param {Object} item current iteration item
|
||||
* @return {Boolean} if false, item will be filtered out
|
||||
*
|
||||
* @author Kir Belevich
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = function(item) {
|
||||
|
||||
return !(item.processinginstruction && item.processinginstruction.name === 'xml');
|
||||
|
||||
exports.fn = () => {
|
||||
return {
|
||||
instruction: {
|
||||
enter: (node, parentNode) => {
|
||||
if (node.name === 'xml') {
|
||||
detachNodeFromParent(node, parentNode);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
113
node_modules/svgo/plugins/reusePaths.js
generated
vendored
Normal file
113
node_modules/svgo/plugins/reusePaths.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @typedef {import('../lib/types').XastElement} XastElement
|
||||
* @typedef {import('../lib/types').XastParent} XastParent
|
||||
* @typedef {import('../lib/types').XastNode} XastNode
|
||||
*/
|
||||
|
||||
const JSAPI = require('../lib/svgo/jsAPI.js');
|
||||
|
||||
exports.type = 'visitor';
|
||||
exports.name = 'reusePaths';
|
||||
exports.active = false;
|
||||
exports.description =
|
||||
'Finds <path> elements with the same d, fill, and ' +
|
||||
'stroke, and converts them to <use> elements ' +
|
||||
'referencing a single <path> def.';
|
||||
|
||||
/**
|
||||
* Finds <path> elements with the same d, fill, and stroke, and converts them to
|
||||
* <use> elements referencing a single <path> def.
|
||||
*
|
||||
* @author Jacob Howcroft
|
||||
*
|
||||
* @type {import('../lib/types').Plugin<void>}
|
||||
*/
|
||||
exports.fn = () => {
|
||||
/**
|
||||
* @type {Map<string, Array<XastElement>>}
|
||||
*/
|
||||
const paths = new Map();
|
||||
|
||||
return {
|
||||
element: {
|
||||
enter: (node) => {
|
||||
if (node.name === 'path' && node.attributes.d != null) {
|
||||
const d = node.attributes.d;
|
||||
const fill = node.attributes.fill || '';
|
||||
const stroke = node.attributes.stroke || '';
|
||||
const key = d + ';s:' + stroke + ';f:' + fill;
|
||||
let list = paths.get(key);
|
||||
if (list == null) {
|
||||
list = [];
|
||||
paths.set(key, list);
|
||||
}
|
||||
list.push(node);
|
||||
}
|
||||
},
|
||||
|
||||
exit: (node, parentNode) => {
|
||||
if (node.name === 'svg' && parentNode.type === 'root') {
|
||||
/**
|
||||
* @type {XastElement}
|
||||
*/
|
||||
const rawDefs = {
|
||||
type: 'element',
|
||||
name: 'defs',
|
||||
attributes: {},
|
||||
children: [],
|
||||
};
|
||||
/**
|
||||
* @type {XastElement}
|
||||
*/
|
||||
const defsTag = new JSAPI(rawDefs, node);
|
||||
let index = 0;
|
||||
for (const list of paths.values()) {
|
||||
if (list.length > 1) {
|
||||
// add reusable path to defs
|
||||
/**
|
||||
* @type {XastElement}
|
||||
*/
|
||||
const rawPath = {
|
||||
type: 'element',
|
||||
name: 'path',
|
||||
attributes: { ...list[0].attributes },
|
||||
children: [],
|
||||
};
|
||||
delete rawPath.attributes.transform;
|
||||
let id;
|
||||
if (rawPath.attributes.id == null) {
|
||||
id = 'reuse-' + index;
|
||||
index += 1;
|
||||
rawPath.attributes.id = id;
|
||||
} else {
|
||||
id = rawPath.attributes.id;
|
||||
delete list[0].attributes.id;
|
||||
}
|
||||
/**
|
||||
* @type {XastElement}
|
||||
*/
|
||||
const reusablePath = new JSAPI(rawPath, defsTag);
|
||||
defsTag.children.push(reusablePath);
|
||||
// convert paths to <use>
|
||||
for (const pathNode of list) {
|
||||
pathNode.name = 'use';
|
||||
pathNode.attributes['xlink:href'] = '#' + id;
|
||||
delete pathNode.attributes.d;
|
||||
delete pathNode.attributes.stroke;
|
||||
delete pathNode.attributes.fill;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (defsTag.children.length !== 0) {
|
||||
if (node.attributes['xmlns:xlink'] == null) {
|
||||
node.attributes['xmlns:xlink'] = 'http://www.w3.org/1999/xlink';
|
||||
}
|
||||
node.children.unshift(defsTag);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user