更新前端静态网页获取方式,放弃使用后端获取api

This commit is contained in:
2025-09-09 10:47:51 +08:00
parent 6889ca37e5
commit 44a4f1bae1
25558 changed files with 2463152 additions and 153 deletions

22
frontend/node_modules/postcss-svgo/LICENSE-MIT generated vendored Normal file
View File

@@ -0,0 +1,22 @@
Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
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.

110
frontend/node_modules/postcss-svgo/README.md generated vendored Normal file
View File

@@ -0,0 +1,110 @@
# [postcss][postcss]-svgo
> Optimise inline SVG with PostCSS.
## Install
With [npm](https://npmjs.org/package/postcss-svgo) do:
```
npm install postcss-svgo --save
```
## Example
### Input
```css
h1 {
background: url('data:image/svg+xml;charset=utf-8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"><circle cx="50" cy="50" r="40" fill="yellow" /></svg>');
}
h2 {
background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNDAiIGZpbGw9InllbGxvdyIgLz48IS0tdGVzdCBjb21tZW50LS0+PC9zdmc+');
}
```
### Output
```css
h1 {
background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="%23ff0"/></svg>');
}
h2 {
background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxjaXJjbGUgY3g9IjUwIiBjeT0iNTAiIHI9IjQwIiBmaWxsPSIjZmYwIi8+PC9zdmc+');
}
```
## API
### `svgo([options])`
#### options
##### encode
Type: `boolean`
Default: `undefined`
If `true`, it will encode URL-unsafe characters such as `<`, `>` and `&`;
`false` will decode these characters, and `undefined` will neither encode nor
decode the original input. Note that regardless of this setting, `#` will
always be URL-encoded.
##### plugins
Optionally, you can customise the output by specifying the `plugins` option. You
will need to provide the config in comma separated objects, like the example
below. Note that you can either disable the plugin by setting it to `false`,
or pass different options to change the default behaviour.
```js
var postcss = require('postcss');
var svgo = require('postcss-svgo');
var opts = {
plugins: [{
removeDoctype: false
}, {
removeComments: false
}, {
cleanupNumericValues: {
floatPrecision: 2
}
}, {
convertColors: {
names2hex: false,
rgb2hex: false
}
}]
};
postcss([ svgo(opts) ]).process(css).then(function (result) {
console.log(result.css)
});
```
You can view the [full list of plugins here][plugins].
## Usage
See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for
examples for your environment.
## Contributors
See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md).
## License
MIT © [Ben Briggs](http://beneb.info)
[postcss]: https://github.com/postcss/postcss
[plugins]: https://github.com/svg/svgo/tree/master/plugins

View File

@@ -0,0 +1 @@
../svgo/bin/svgo

View 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

View 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.

View File

@@ -0,0 +1,917 @@
# Commander.js
[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](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)

View 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;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}

View 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
}

View 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;

View File

@@ -0,0 +1,590 @@
## 1.1.3 (March 31, 2021)
- Fixed matching on CSS wide keywords for at-rule's prelude and descriptors
- Added `fit-content` to `width` property patch as browsers are supported it as a keyword (nonstandard), but spec defines it as a function
- Fixed parsing a value contains parentheses or brackets and `parseValue` option is set to `false`, in that case `!important` was included into a value but must not (#155)
## 1.1.2 (November 26, 2020)
- Rolled back to use spread syntax in object literals since it not supported by nodejs < 8.3 (#145)
## 1.1.1 (November 18, 2020)
- Fixed edge cases in mismatch location computation for `SyntaxMatchError`
## 1.1.0 (November 17, 2020)
- Bumped `mdn-data` to 2.0.14
- Extended `fork()` method to allow append syntax instead of overriding for `types`, `properties` and `atrules`, e.g. `csstree.fork({ types: { color: '| foo | bar' } })`
- Extended lexer API for validation
- Added `Lexer#checkAtruleName(atruleName)`, `Lexer#checkAtrulePrelude(atruleName, prelude)`, `Lexer#checkAtruleDescriptorName(atruleName, descriptorName)` and `Lexer#checkPropertyName(propertyName)`
- Added `Lexer#getAtrule(atruleName, fallbackBasename)` method
- Extended `Lexer#getAtrulePrelude()` and `Lexer#getProperty()` methods to take `fallbackBasename` parameter
- Improved `SyntaxMatchError` location details
- Changed error messages
## 1.0.1 (November 11, 2020)
- Fixed edge cases for parsing of custom property value with a single whitespace when `parseCustomProperty:true`
## 1.0.0 (October 27, 2020)
- Added `onComment` option to parser config
- Added support for `break` and `skip` values in `walk()` to control traversal
- Added `List#reduce()` and `List#reduceRight()` methods
- Bumped `mdn-data` to 2.0.12
- Exposed version of the lib (i.e. `import { version } from 'css-tree'`)
- Fixed `Lexer#dump()` to dump atrules syntaxes as well
- Fixed matching comma separated `<urange>` list (#135)
- Renamed `HexColor` node type into `Hash`
- Removed `element()` specific parsing rules
- Removed `dist/default-syntax.json` from package
## 1.0.0-alpha.39 (December 5, 2019)
- Fixed walker with `visit: "Declaration"` to iterate `DeclarationList` (#114)
## 1.0.0-alpha.38 (November 25, 2019)
- Bumped `mdn-data` to `2.0.6`
- Added initial implmentation for at-rule matching via `Lexer#matchAtrulePrelude()` and `Lexer#matchAtruleDescriptor()` methods
- Added `-moz-control-character-visibility`, `-ms-grid-columns`, `-ms-grid-rows` and `-ms-hyphenate-limit-last` properties to patch (#111)
- Added `flow`, `flow-root` and `table-caption` values to patched `display` (#112)
## 1.0.0-alpha.37 (October 22, 2019)
- Bumped `source-map` version to `^0.6.1` to fix source map generation inconsistency across node.js versions due to mappings sorting bug and v8 moving to [a stable Array#sort](https://v8.dev/blog/array-sort) ([fix commit](https://github.com/mozilla/source-map/commit/f35a2e4212dd025cb5e1fc219e7ac8a4b96c2cc9) in `source-map`)
## 1.0.0-alpha.36 (October 13, 2019)
- Dropped support for Node < 8
- Updated dev deps (fixed `npm audit` issues)
- Reworked build pipeline
- Package provides `dist/csstree.js` and `dist/csstree.min.js` now (instead of single `dist/csstree.js` that was a min version)
- Bundle size (min version) reduced from 191Kb to 158Kb due to some optimisations
- Definition syntax
- Renamed `grammar` into `definitionSyntax` (named per spec)
- Added `compact` option to `generate()` method to avoid formatting (spaces) when possible
- Lexer
- Changed `dump()` method to produce syntaxes in compact form by default
## 1.0.0-alpha.35 (October 7, 2019)
- Walker
- Changed implementation to avoid runtime compilation due to CSP issues (see #91, #109)
- Added `find()`, `findLast()` and `findAll()` methods (e.g. `csstree.find(ast, node => node.type === 'ClassSelector')`)
## 1.0.0-alpha.34 (July 27, 2019)
- Tokenizer
- Added `isBOM()` function
- Added `charCodeCategory()` function
- Removed `firstCharOffset()` function (use `isBOM()` instead)
- Removed `CHARCODE` dictionary
- Removed `INPUT_STREAM_CODE*` dictionaries
- Lexer
- Allowed comments in matching value (just ignore them like whitespaces)
- Increased iteration count in value matching from 10k up to 15k
- Fixed missed `debugger` (#104)
## 1.0.0-alpha.33 (July 11, 2019)
- Lexer
- Fixed low priority productions matching by changing an approach for robust one (#103)
## 1.0.0-alpha.32 (July 11, 2019)
- Lexer
- Fixed low priority productions matching in long `||-` and `&&-` groups (#103)
## 1.0.0-alpha.31 (July 11, 2019)
- Bumped `mdn/data` to `2.0.4` (#99)
- Lexer
- Added [bracketed range notation](https://drafts.csswg.org/css-values-4/#numeric-ranges) support and related refactoring
- Removed `<number-zero-one>`, `<number-one-or-greater>` and `<positive-integer>` from generic types. In fact, types moved to patch, because those types can be expressed in a regular grammar due to bracketed range notation implemented
- Added support for multiple token string matching
- Improved `<custom-ident>` production matching to claim the keyword only if no other unfulfilled production can claim it (#101)
- Improved `<length>` production matching to claim "unitless zero" only if no other unfulfilled production can claim it
- Changed lexer's constructor to prevent generic types override when used
- Fixed large `||`- and `&&`-group matching, matching continues from the beginning on term match (#85)
- Fixed checking that value has `var()` occurrences when value is a string (such values can't be matched on syntax currently and fail with specific error that can be used for ignorance in validation tools)
- Fixed `<declaration-value>` and `<any-value>` matching when a value contains a function, parentheses or braces
## 1.0.0-alpha.30 (July 3, 2019)
- Bumped `mdn/data` to `~2.0.3`
- Removed type removals from `mdn/data` due to lack of some generic types and specific lexer restictions (since lexer was reworked, see below)
- Reduced and updated patches
- Tokenizer
- Reworked tokenizer itself to compliment [CSS Syntax Module Level 3](https://drafts.csswg.org/css-syntax/#tokenization)
- `Tokenizer` class splitted into several abstractions:
- Added `TokenStream` class
- Added `OffsetToLocation` class
- Added `tokenize()` function that creates `TokenStream` instance for given string or updates a `TokenStream` instance passed as second parameter
- Removed `Tokenizer` class
- Removed `Raw` token type
- Renamed `Identifier` token type to `Ident`
- Added token types: `Hash`, `BadString`, `BadUrl`, `Delim`, `Percentage`, `Dimension`, `Colon`, `Semicolon`, `Comma`, `LeftSquareBracket`, `RightSquareBracket`, `LeftParenthesis`, `RightParenthesis`, `LeftCurlyBracket`, `RightCurlyBracket`
- Replaced `Punctuator` with `Delim` token type, that excludes specific characters with its own token type like `Colon`, `Semicolon` etc
- Removed `findCommentEnd`, `findStringEnd`, `findDecimalNumberEnd`, `findNumberEnd`, `findEscapeEnd`, `findIdentifierEnd` and `findUrlRawEnd` helper function
- Removed `SYMBOL_TYPE`, `PUNCTUATION` and `STOP_URL_RAW` dictionaries
- Added `isDigit`, `isHexDigit`, `isUppercaseLetter`, `isLowercaseLetter`, `isLetter`, `isNonAscii`, `isNameStart`, `isName`, `isNonPrintable`, `isNewline`, `isWhiteSpace`, `isValidEscape`, `isIdentifierStart`, `isNumberStart`, `consumeEscaped`, `consumeName`, `consumeNumber` and `consumeBadUrlRemnants` helper functions
- Parser
- Changed parsing algorithms to work with new token type set
- Changed `HexColor` consumption in way to relax checking a value, i.e. now `value` is a sequence of one or more name chars
- Added `&` as a property hack
- Relaxed `var()` parsing to only check that a first arguments is an identifier (not a custom property name as before)
- Lexer
- Reworked syntax matching to relay on token set only (having AST is optional now)
- Extended `Lexer#match()`, `Lexer#matchType()` and `Lexer#matchProperty()` methods to take a string as value, beside AST as a value
- Extended `Lexer#match()` method to take a string as a syntax, beside of syntax descriptor
- Reworked generic types:
- Removed `<attr()>`, `<url>` (moved to patch) and `<progid>` types
- Added types:
- Related to token types: `<ident-token>`, `<function-token>`, `<at-keyword-token>`, `<hash-token>`, `<string-token>`, `<bad-string-token>`, `<url-token>`, `<bad-url-token>`, `<delim-token>`, `<number-token>`, `<percentage-token>`, `<dimension-token>`, `<whitespace-token>`, `<CDO-token>`, `<CDC-token>`, `<colon-token>`, `<semicolon-token>`, `<comma-token>`, `<[-token>`, `<]-token>`, `<(-token>`, `<)-token>`, `<{-token>` and `<}-token>`
- Complex types: `<an-plus-b>`, `<urange>`, `<custom-property-name>`, `<declaration-value>`, `<any-value>` and `<zero>`
- Renamed `<unicode-range>` to `<urange>` as per spec
- Renamed `<expression>` (IE legacy extension) to `<-ms-legacy-expression>` and may to be removed in next releases
## 1.0.0-alpha.29 (May 30, 2018)
- Lexer
- Syntax matching was completely reworked. Now it's token-based and uses state machine. Public API has not changed. However, some internal data structures have changed. Most significal change in syntax match result tree structure, it's became token-based instead of node-based.
- Grammar
- Changed grammar tree format:
- Added `Token` node type to represent a single code point (`<delim-token>`)
- Added `Multiplier` that wraps a single node (`term` property)
- Added `AtKeyword` to represent `<at-keyword-token>`
- Removed `Slash` and `Percent` node types, they are replaced for a node with `Token` type
- Changed `Function` to represent `<function-token>` with no children
- Removed `multiplier` property from `Group`
- Changed `generate()` method:
- Method takes an `options` as second argument now (`generate(node, forceBraces, decorator)` -> `generate(node, options)`). Two options are supported: `forceBraces` and `decorator`
- When a second parameter is a function it treats as `decorate` option value, i.e. `generate(node, fn)` -> `generate(node, { decorate: fn })`
- Decorate function invokes with additional parameter a reference to a node
- Tokenizer
- Renamed `Atrule` const to `AtKeyword`
## 1.0.0-alpha.28 (February 19, 2018)
- Renamed `lexer.grammar.translate()` method into `generate()`
- Fixed `<'-webkit-font-smoothing'>` and `<'-moz-osx-font-smoothing'>` syntaxes (#75)
- Added vendor keywords for `<'overflow'>` property syntax (#76)
- Pinned `mdn-data` to `~1.1.0` and fixed issues with some updated property syntaxes
## 1.0.0-alpha.27 (January 14, 2018)
- Generator
- Changed node's `generate()` methods invocation, methods now take a node as a single argument and context (i.e. `this`) that have methods: `chunk()`, `node()` and `children()`
- Renamed `translate()` to `generate()` and changed to take `options` argument
- Removed `translateMarkup(ast, enter, leave)` method, use `generate(ast, { decorator: (handlers) => { ... }})` instead
- Removed `translateWithSourceMap(ast)`, use `generate(ast, { sourceMap: true })` instead
- Changed to support for children as an array
- Walker
- Changed `walk()` to take an `options` argument instead of handler, with `enter`, `leave`, `visit` and `reverse` options (`walk(ast, fn)` is still works and equivalent to `walk(ast, { enter: fn })`)
- Removed `walkUp(ast, fn)`, use `walk(ast, { leave: fn })`
- Removed `walkRules(ast, fn)`, use `walk(ast, { visit: 'Rule', enter: fn })` instead
- Removed `walkRulesRight(ast, fn)`, use `walk(ast, { visit: 'Rule', reverse: true, enter: fn })` instead
- Removed `walkDeclarations(ast, fn)`, use `walk(ast, { visit: 'Declaration', enter: fn })` instead
- Changed to support for children as array in most cases (`reverse: true` will fail on arrays since they have no `forEachRight()` method)
- Misc
- List
- Added `List#forEach()` method
- Added `List#forEachRight()` method
- Added `List#filter()` method
- Changed `List#map()` method to return a `List` instance instead of `Array`
- Added `List#push()` method, similar to `List#appendData()` but returns nothing
- Added `List#pop()` method
- Added `List#unshift()` method, similar to `List#prependData()` but returns nothing
- Added `List#shift()` method
- Added `List#prependList()` method
- Changed `List#insert()`, `List#insertData()`, `List#appendList()` and `List#insertList()` methods to return a list that performed an operation
- Changed `keyword()` method
- Changed `name` field to include a vendor prefix
- Added `basename` field to contain a name without a vendor prefix
- Added `custom` field that contain a `true` when keyword is a custom property reference
- Changed `property()` method
- Changed `name` field to include a vendor prefix
- Added `basename` field to contain a name without any prefixes, i.e. a hack and a vendor prefix
- Added `vendorPrefix()` method
- Added `isCustomProperty()` method
## 1.0.0-alpha.26 (November 9, 2017)
- Tokenizer
- Added `Tokenizer#isBalanceEdge()` method
- Removed `Tokenizer.endsWith()` method
- Parser
- Made the parser tolerant to errors by default
- Removed `tolerant` parser option (no parsing modes anymore)
- Removed `property` parser option (a value parsing does not depend on property name anymore)
- Canceled error for a handing semicolon in a block
- Canceled error for unclosed `Brackets`, `Function` and `Parentheses` when EOF is reached
- Fixed error when prelude ends with a comment for at-rules with custom prelude consumer
- Relaxed at-rule parsing:
- Canceled error when EOF is reached after a prelude
- Canceled error for an at-rule with custom block consumer when at-rule has no block (just don't apply consumer in that case)
- Canceled error on at-rule parsing when it occurs outside prelude or block (at-rule is converting to `Raw` node)
- Allowed for any at-rule to have a prelude and a block, even if it's invalid per at-rule syntax (the responsibility for this check is moved to lexer, since it's possible to construct a AST with such errors)
- Made a declaration value a safe parsing point (i.e. error on value parsing lead to a value is turning into `Raw` node, not a declaration as before)
- Excluded surrounding white spaces and comments from a `Raw` node that represents a declaration value
- Changed `Value` parse handler to return a node only with type `Value` (previously it returned a `Raw` node in some cases)
- Fixed issue with `onParseError()` is not invoked for errors occured on selector or declaration value parsing in some cases
- Changed using of `onParseError()` to stop parsing if handler throws an exception
- Lexer
- Changed `grammar.walk()` to invoke passed handler on entering to node rather than on leaving the node
- Improved `grammar.walk()` to take a walk handler pair as an object, i.e. `walk(node, { enter: fn, leave: fn })`
- Changed `Lexer#match*()` methods to take a node of any type, but with a `children` field
- Added `Lexer#match(syntax, node)` method
- Fixed `Lexer#matchType()` method to stop return a positive result for the CSS wide keywords
## 1.0.0-alpha25 (October 9, 2017)
- Parser
- Added fallback node as argument to `onParseError()` handler
- Fixed raw consuming in tolerant mode when selector is invalid (greedy consuming and redundant warnings)
- Fixed exception in tolerant mode caused by unknown at-rule with unclosed block
- Changed handling of semicolons:
- Hanging semicolon inside declaration blocks raise an error or turns into a `Raw` node in tolerant mode instead of being ignored
- Semicolon outside of declaration blocks opens a `Rule` node as part of selector instead of being ignored
- Aligned `parseAtrulePrelude` behaviour to `parseRulePrelude`
- Removed `Raw` node wraping into `AtrulePrelude` when `parseAtrulePrelude` is disabled
- Removed error emitting when at-rule has a custom prelude customer but no prelude is found (it should be validated by a lexer later)
- Generator
- Fixed performance issue with `translateWithSourceMap()`, flattening the string (because of mixing building string and indexing into it) turned it into a quadratic algorithm (approximate numbers can be found in [the quiz created by this case](https://gist.github.com/lahmatiy/ea25d0e623d88ca9848384b5707d52d9))
- Added support for a single solidus hack for `property()`
- Minor fixes for custom errors
## 1.0.0-alpha24 (September 14, 2017)
- Improved CSSTree to be stable for standart build-in objects extension (#58)
- Parser
- Renamed rule's `selector` to `prelude`. The reasons: [spec names this part so](https://www.w3.org/TR/css-syntax-3/#qualified-rule), and this branch can contain not only a selector (`SelectorList`) but also a raw payload (`Raw`). What's changed:
- Renamed `Rule.selector` to `Rule.prelude`
- Renamed `parseSelector` parser option to `parseRulePrelude`
- Removed option for selector parse in `SelectorList`
- Lexer
- Fixed undefined positions in a error when match a syntax to empty or white space only value
- Improved `Lexer#checkStructure()`
- Return a warning as an object with node reference and message
- No exception on unknown node type, return a warning instead
## 1.0.0-alpha23 (September 10, 2017)
- Fixed `Tokenizer#getRawLength()`'s false positive balance match to the end of input in some cases (#56)
- Rename walker's entry point methods to be the same as CSSTree exposed methods (i.e. `walk()`, `walkUp()` etc)
- Rename at-rule's `expression` to `prelude` (since [spec names it so](https://www.w3.org/TR/css-syntax-3/#at-rule))
- `AtruleExpression` node type → `AtrulePrelude`
- `Atrule.expression` field → `Atrule.prelude`
- `parseAtruleExpression` parser's option → `parseAtrulePrelude`
- `atruleExpression` parse context → `atrulePrelude`
- `atruleExpression` walk context reference → `atrulePrelude`
## 1.0.0-alpha22 (September 8, 2017)
- Parser
- Fixed exception on parsing of unclosed `{}-block` in tolerant mode
- Added tolerant mode support for `DeclarationList`
- Added standalone entry point, i.e. default parser can be used via `require('css-tree/lib/parser')` (#47)
- Generator
- Changed generator to produce `+n` when `AnPlusB.a` is `+1` to be "round-trip" with parser
- Added standalone entry point, i.e. default generators can be used via `require('css-tree/lib/generator')`
- Walker
- Added standalone entry point, i.e. default walkers can be used via `require('css-tree/lib/walker')` (#47)
- Lexer
- Added `default` keyword to the list of invalid values for `<custom-ident>` (since it reversed per [spec](https://www.w3.org/TR/css-values/#custom-idents))
- Convertors (`toPlainObject()` and `fromPlainObject()`) moved to `lib/convertor` (entry point is `require('css-tree/lib/convertor')`)
## 1.0.0-alpha21 (September 5, 2017)
- Tokenizer
- Added `Raw` token type
- Improved tokenization of `url()` with raw as url to be more spec complient
- Added `Tokenizer#balance` array computation on token layout
- Added `Tokenizer#getRawLength()` to compute a raw length with respect of block balance
- Added `Tokenizer#getTokenStart(offset)` method to get token start offset by token index
- Added `idx` and `balance` fields to each token of `Tokenizer#dump()` method result
- Parser
- Added `onParseError` option
- Reworked node parsers that consume a `Raw` node to use a new approach. Since now a `Raw` node builds in `parser#Raw()` function only
- Changed semantic of `parser#Raw()`, it takes 5 parameters now (it might to be changed in future)
- Changed `parser#tolerantParse()` to pass a start token index to fallback function instead of source offset
- Fixed `AtruleExpression` consuming in tolerant mode
- Atrule handler to convert an empty `AtruleExpression` node into `null`
- Changed `AtruleExpression` handler to always return a node (before it could return a `null` in some cases)
- Lexer
- Fixed comma match node for `#` multiplier
- Added reference name to `SyntaxReferenceError`
- Additional fixes on custom errors
- Reduced possible corruption of base config by `syntax.fork()`
## 1.0.0-alpha20 (August 28, 2017)
- Tokenizer
- Added `Atrule` token type (`<at-rule-token>` per spec)
- Added `Function` token type (`<function-token>` per spec)
- Added `Url` token type
- Replaced `Tokenizer#getTypes()` method with `Tokenizer#dump()` to get all tokens as an array
- Renamed `Tokenizer.TYPE.Whitespace` to `Tokenizer.TYPE.WhiteSpace`
- Renamed `Tokenizer.findWhitespaceEnd()` to `Tokenizer.findWhiteSpaceEnd()`
- Parser
- Added initial implementation of tollerant mode (turn on by passing `tolerant: true` option). In this mode parse errors are never occour and any invalid part of CSS turns into a `Raw` node. Current safe points: `Atrule`, `AtruleExpression`, `Rule`, `Selector` and `Declaration`. Feature is experimental and further improvements are planned.
- Changed `Atrule.expression` to contain a `AtruleExpression` node or `null` only (other node types is wrapping into a `AtruleExpression` node)
- Renamed `AttributeSelector.operator` to `AttributeSelector.matcher`
- Generator
- `translate()` method is now can take a function as second argument, that recieves every generated chunk. When no function is passed, default handler is used, it concats all the chunks and method returns a string.
- Lexer
- Used [mdn/data](https://github.com/mdn/data) package as source of lexer's grammar instead of local dictionaries
- Added `x` unit to `<resolution>` generic type
- Improved match tree:
- Omited Group (sequences) match nodes
- Omited empty match nodes (for terms with `zero or more` multipliers)
- Added `ASTNode` node type to contain a reference to AST node
- Fixed node duplication (uncompleted match were added to tree)
- Added AST node reference in match nodes
- Added comma match node by `#` multiplier
- Grammar
- Changed `translate()` function to get a handler as third argument (optional). That handler recieves result of node traslation and can be used for decoration purposes. See [example](https://github.com/csstree/docs/blob/04c65af44477b5ea05feb373482898122b2a4528/docs/syntax.html#L619-L627)
- Added `SyntaxParseError` to grammar export
- Reworked group and multipliers representation in syntax tree:
- Replaced `Sequence` for `Group` node type (`Sequence` node type removed)
- Added `explicit` boolean property for `Group`
- Only groups can have a multiplier now (other node types is wrapping into a single term implicit group when multiplier is applied)
- Renamed `nonEmpty` Group's property to `disallowEmpty`
- Added optimisation for syntax tree by dropping redundant root `Group` when it contains a single `Group` term (return this `Group` as a result)
- Changed lexer's match functionality
- Changed `Lexer#matchProperty()` and `Lexer#matchType()` to return an object instead of match tree. A match tree stores in `matched` field when AST is matched to grammar successfully, otherwise an error in `error` field. The result object also has some methods to test AST node against a match tree: `getTrace()`, `isType()`, `isProperty()` and `isKeyword()`
- Added `Lexer#matchDeclaration()` method
- Removed `Lexer#lastMatchError` (error stores in match result object in `error` field)
- Added initial implementation of search for AST segments (new lexer methods: `Lexer#findValueSegments()`, `Lexer#findDeclarationValueSegments()` and `Lexer#findAllSegments`)
- Implemented `SyntaxReferenceError` for unknown property and type references
- Renamed field in resulting object of `property()` function: `variable``custom`
- Fixed issue with readonly properties (e.g. `line` and `column`) of `Error` and exception on attempt to write in iOS Safari
## 1.0.0-alpha19 (April 24, 2017)
- Extended `List` class with new methods:
- `List#prepend(item)`
- `List#prependData(data)`
- `List#insertData(data)`
- `List#insertList(list)`
- `List#replace(item, itemOrList)`
## 1.0.0-alpha18 (April 3, 2017)
- Added `atrule` walk context (#39)
- Changed a result of generate method for `AnPlusB`, `AttributeSelector`, `Function`, `MediaFeature` and `Ratio` ([1e95877](https://github.com/csstree/csstree/commit/1e9587710efa8e9338bcf0bc794b4b45f286231d))
- Fixed typo in `List` exception messages (@strarsis, #42)
- Improved tokenizer to convert an input to a string
## 1.0.0-alpha17 (March 13, 2017)
- Implemented new concept of `syntax`
- Changed main `exports` to expose a default syntax
- Defined initial [CSS syntax](lib/syntax/default.js)
- Implemented `createSyntax()` method to create a new syntax from scratch
- Implemented `fork()` method to create a new syntax based on given via extension
- Parser
- Implemented `mediaQueryList` and `mediaQuery` parsing contexts
- Implemented `CDO` and `CDC` node types
- Implemented additional declaration property prefix hacks (`#` and `+`)
- Added support for UTF-16LE BOM
- Added support for `@font-face` at-rule
- Added `chroma()` to legacy IE filter functions
- Improved `HexColor` to consume hex only
- Improved support for `\0` and `\9` hacks (#2)
- Relaxed number check for `Ratio` terms
- Allowed fractal values as a `Ratio` term
- Disallowed zero number as a `Ratio` term
- Changed important clause parsing
- Allowed any identifier for important (to support hacks like `!ie`)
- Store `true` for `important` field in case identifier equals to `important` and string otherwise
- Fixed parse error formatted message rendering to take into account tabs
- Removed exposing of `Parser` class
- Removed `readSelectorSequence()`, `readSequenceFallback()` and `readSelectorSequenceFallback` methods
- Used single universal sequence consumer for `AtruleExpression`, `Selector` and `Value`
- Generator
- Reworked generator to use auto-generated functions based on syntax definition (additional work to be done in next releases)
- Implemented `translateMarkup(ast, before, after)` method for complex cases
- Reworked `translateWithSourceMap` to be more flexible (based on `translateMarkup`, additional work to be done in next releases)
- Walker
- Reworked walker to use auto-generated function based on syntax definition (additional work to be done in next releases)
- Lexer
- Prepared for better extensibility (additional work to be done in next releases)
- Implemented `checkStructure(ast)` method to check AST structure based on syntax definition
- Update syntax dictionaries to latest `mdn/data`
- Add missing `<'offset-position'>` syntax
- Extended `<position>` property with `-webkit-sticky` (@sergejmueller, #37)
- Improved mismatch error position
- Implemented script (`gen:syntax`) to generate AST format reference page (`docs/ast.md`) using syntax definition
## 1.0.0-alpha16 (February 12, 2017)
- Exposed `Parser` class
- Added `startOffset` option to `Tokenizer` (constructor and `setSource()` method)
- Added fallback functions for default (`readSequenceFallback`) and selector (`readSelectorSequenceFallback`) sequence readers
- Fixed edge cases for `AnPlusB`
- Fixed wrong whitespace ignoring in `Selector` consumer
## 1.0.0-alpha15 (February 8, 2017)
- Fixed broken `atruleExpression` context
- Fixed vendor prefix detection in `keyword()` and `property()`
- Fixed `property()` to not lowercase custom property names
- Added `variable` boolean flag in `property()` result
- Renamed `scanner` into `tokenizer`
- Ranamed `syntax` into `lexer`
- Moved `docs/*.html` files to [csstree/docs](https://github.com/csstree/docs) repo
- Added `element()` function for `Value` context (`-moz-element()` supported as well)
- Merged `Universal` node type into `Type`
- Renamed node types:
- `Id` -> `IdSelector`
- `Class` -> `ClassSelector`
- `Type` -> `TypeSelector`
- `Attribute` -> `AttributeSelector`
- `PseudoClass` -> `PseudoClassSelector`
- `PseudoElement` -> `PseudoElementSelector`
- `Hash` -> `HexColor`
- `Space` -> `WhiteSpace`
- `An+B` -> `AnPlusB`
- Removed `Progid` node type
- Relaxed `MediaQuery` consumer to not validate syntax on parse and to include whitespaces in children sequence as is
- Added `WhiteSpace.value` property to store whitespace sequence
- Implemented parser options to specify what should be parsed in details (when option is `false` some part of CSS represents as balanced `Raw`):
- `parseAtruleExpression` to parse at-rule expressions (`true` by default)
- `parseSelector` to parse rule's selector (`true` by default)
- `parseValue` - to parse declaration's value (`true` by default)
- `parseCustomProperty` to parse value and fallback of custom property (`false` by default)
- Changed tokenization to stick leading hyphen minus to identifier token
- Changed selector parsing:
- Don't convert spaces into descendant combinator
- Don't validate selector structure on parsing (selectors may be checked by lexer later)
- Initial refactoring of [docs](https://github.com/csstree/csstree/blob/master/docs)
- Various improvements and fixes
## 1.0.0-alpha14 (February 3, 2017)
- Implemented `DeclarationList`, `MediaQueryList`, `MediaQuery`, `MediaFeature` and `Ratio` node types
- Implemented `declarationList` context (useful to parse HTML `style` attribute content)
- Implemented custom consumers for `@import`, `@media`, `@page` and `@supports` at-rules
- Implemented `atrule` option for `parse()` config, is used for `atruleExpession` context to specify custom consumer for at-rule if any
- Added `Scanner#skipWS()`, `Scanner#eatNonWS()`, `Scanner#consume()` and `Scanner#consumeNonWS()` helper methods
- Added custom consumers for known functional-pseudos, consume unknown functional-pseudo content as balanced `Raw`
- Allowed any `PseudoElement` to be a functional-pseudo (#33)
- Improved walker implementations to reduce GC thrashing by reusing cursors
- Changed `Atrule.block` to contain a `Block` node type only if any
- Changed `Block.loc` positions to include curly brackets
- Changed `Atrule.expression` to store a `null` if no expression
- Changed parser to use `StyleSheet` node type only for top level node (when context is `stylesheet`, that's by default)
- Changed `Parentheses`, `Brackets` and `Function` consumers to use passed sequence reader instead of its own
- Changed `Value` and `AtruleExpression` consumers to use common sequence reader (that reader was used by `Value` consumer before)
- Changed default sequence reader to exclude storage of spaces around `Comma`
- Changed processing of custom properties:
- Consume declaration value as balanced `Raw`
- Consume `var()` fallback value as balanced `Raw`
- Validate first argument of `var()` starts with double dash
- Custom property's value and fallback includes spaces around
- Fixed `Nth` to have a `loc` property
- Fixed `SelectorList.loc` and `Selector.loc` positions to exclude spaces
- Fixed issue Browserify build fail with `default-syntax.json` is not found error (#32, @philschatz)
- Disallowed `Type` selector starting with dash (parser throws an error in this case now)
- Disallowed empty selectors for `Rule` (not sure if it's correct but looks reasonable)
- Removed `>>` combinator support until any browser support (no signals about that yet)
- Removed `PseudoElement.legacy` property
- Removed special case for `:before`, `:after`, `:first-letter` and `:first-line` to represent them as `PseudoElement`, now those pseudos are represented as `PseudoClass` nodes
- Removed deprecated `Syntax#match()` method
- Parser was splitted into modules and related changes, one step closer to an extensible parser
- Various fixes and improvements, all changes have negligible impact on performance
## 1.0.0-alpha13 (January 19, 2017)
- Changed location storing in `SyntaxMatchError`
- Changed property to store mismatch offset to `mismatchOffset`
- Changed `offset` property to store bad node offset in source CSS if any
- Added `loc` property that stores bad node `loc` if any
## 1.0.0-alpha12 (January 19, 2017)
- Fixed `Syntax#matchProperty()` method to always return a positive result for custom properties since syntax is never defined for them (#31)
- Implemented `fromPlainObject()` and `toPlainObject()` to convert plain object to AST or AST to plain object (currently converts `List` <-> `Array`)
## 1.0.0-alpha11 (January 18, 2017)
- Added support for `:matches(<selector-list>)` (#28)
- Added support for `:has(<relative-selector-list>)`
- Added support for `::slotted(<compound-selector>)`
- Implemented `Brackets` node type
- Implemented basic support for at-rule inside rule block (#24)
- Renamed `Selector` node type to `SelectorList`
- Renamed `SimpleSelector` node type to `Selector`
- Renamed `UnicodeRange.name` property to `UnicodeRange.value`
- Replaced `Negation` node type for regular `PseudoClass`
- Unified name of node property to store nested nodes, it always `children` now:
- `StyleSheet.rules` -> `StyleSheet.children`
- `SelectorList.selectors` -> `SelectorList.children`
- `Block.declarations` -> `Block.children`
- `*.sequence` -> `*.children`
- Fixed edge cases in parsing `Hex` and `UnicodeRange` when number not an integer
- Changed `nth-` pseudos parsing
- Implemented `An+B` node type to represent expressions like `2n + 1` or `-3n`
- Fixed edge cases when `a` or `b` is not an integer
- Changed `odd` and `even` keywords processing, keywords are storing as `Identifier` node type now
- Changed `Nth` node type format to store a `nth`-query and an optional `selector`
- Implemented `of` clause for `nth-` pseudos (a.e. `:nth-child(2n + 1 of li, img)`)
- Limited `Nth` parsing rules to `:nth-child()`, `:nth-last-child()`, `:nth-of-type()` and `:nth-last-of-type()` pseudos
- Changed the way to store locations
- Renamed `info` node property to `loc`
- Changed format of `loc` to store `start` and `end` positions
## 1.0.0-alpha10 (January 11, 2017)
- Reworked `Scanner` to be a single point to its functionality
- Exposed `Scanner` class to be useful for external projects
- Changed `walk()` function behaviour to traverse AST nodes in natural order
- Implemented `walkUp()` function to traverse AST nodes from deepest to parent (behaves as `walk()` before)
## 1.0.0-alpha9 (December 21, 2016)
- Fixed `<angle>` generic according to specs that allow a `<number>` equals to zero to be used as valid value (#30)
## 1.0.0-alpha8 (November 11, 2016)
- Fixed `Scanner#skip()` issue method when cursor is moving to the end of source
- Simplified `Progid` node
- Changed behaviour for bad selector processing, now parsing fails instead of selector ignoring
- Fixed `<id-selector>` generic syntax
- Added `q` unit for `<length>` generic syntax
- Refactored syntax parser (performance)
- Reduced startup time by implementing lazy syntax parsing (default syntax doesn't parse on module load)
- Updated syntax dictionaries and used [`mdn/data`](https://github.com/mdn/data) instead of `Template:CSSData`
- Renamed `syntax.stringify()` method to `syntax.translate()`
- Simplified generic syntax functions, those functions receive a single AST node for checking and should return `true` or `false`
- Added exception for values that contains `var()`, those values are always valid for now
- Added more tests and increase code coverage to `98.5%`
## 1.0.0-alpha7 (October 7, 2016)
- Added support for explicit descendant combinator (`>>`)
- Implemented `Type` and `Universal` type nodes
- Improved `Number` parsing by including sign and exponent (#26)
- Parse `before`, `after`, `first-letter` and `first-line` pseudos with single colon as `PseudoElement`
- Changed `FunctionalPseudo` node type to `PseudoClass`
- Fixed attribute selector name parsing (namespace edge cases)
- Fixed location calculation for specified offset when `eof` is reached
- Added more non-standard colors (#25)
- Removed obsolete `Syntax#getAll()` method
- Fixed various edge cases, code clean up and performance improvements
## 1.0.0-alpha6 (September 23, 2016)
- More accurate positions for syntax mismatch errors
- Added [`apple`](https://webkit.org/blog/3709/using-the-system-font-in-web-content/) specific font keywords (#20)
- Changed `Property` node stucture from object to string
- Renamed `Ruleset` node type to `Rule`
- Removed `Argument` node type
- Fixed `Dimension` and `Percentage` position computation
- Fixed bad selector parsing (temporary solution)
- Fixed location computation for CSS with very long lines that may lead to really long parsing with `positions:true` (even freeze)
- Fixed `line` and `column` computation for `SyntaxMatch` error
- Improved performance of parsing and translation. Now CSSTree is under 10ms in [PostCSS benchmark](https://github.com/postcss/benchmark).

View File

@@ -0,0 +1,19 @@
Copyright (C) 2016-2019 by Roman Dvornov
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.

View File

@@ -0,0 +1,130 @@
<img align="right" width="111" height="111"
alt="CSSTree logo"
src="https://cloud.githubusercontent.com/assets/270491/19243723/6f9136c6-8f21-11e6-82ac-eeeee4c6c452.png"/>
# CSSTree
[![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree)
[![Build Status](https://travis-ci.org/csstree/csstree.svg?branch=master)](https://travis-ci.org/csstree/csstree)
[![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master)
[![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree)
[![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree)
CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C specs compliant, with focus on CSS analyzing and source-to-source transforming tasks.
> NOTE: The library isn't in final shape and needs further improvements (e.g. AST format and API are subjects to change in next major versions). However it's stable enough and used by projects like [CSSO](https://github.com/css/csso) (CSS minifier) and [SVGO](https://github.com/svg/svgo) (SVG optimizer) in production.
## Features
- **Detailed parsing with an adjustable level of detail**
By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts.
- **Tolerant to errors by design**
Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later.
- **Fast and efficient**
CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment.
- **Syntax validation**
The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.
## Documentation
- [AST format](docs/ast.md)
- [Parsing CSS → AST](docs/parsing.md)
- [parse(source[, options])](docs/parsing.md#parsesource-options)
- [Serialization AST → CSS](docs/generate.md)
- [generate(ast[, options])](docs/generate.md#generateast-options)
- [AST traversal](docs/traversal.md)
- [walk(ast, options)](docs/traversal.md#walkast-options)
- [find(ast, fn)](docs/traversal.md#findast-fn)
- [findLast(ast, fn)](docs/traversal.md#findlastast-fn)
- [findAll(ast, fn)](docs/traversal.md#findallast-fn)
- [Utils for AST](docs/utils.md)
- [property(name)](docs/utils.md#propertyname)
- [keyword(name)](docs/utils.md#keywordname)
- [clone(ast)](docs/utils.md#cloneast)
- [fromPlainObject(object)](docs/utils.md#fromplainobjectobject)
- [toPlainObject(ast)](docs/utils.md#toplainobjectast)
- [Value Definition Syntax](docs/definition-syntax.md)
- [parse(source)](docs/definition-syntax.md#parsesource)
- [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context)
- [generate(node, options)](docs/definition-syntax.md#generatenode-options)
- [AST format](docs/definition-syntax.md#ast-format)
## Tools
* [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) explore CSSTree AST format with zero setup
* [CSS syntax reference](https://csstree.github.io/docs/syntax.html)
* [CSS syntax validator](https://csstree.github.io/docs/validator.html)
## Related projects
* [csstree-validator](https://github.com/csstree/validator)  NPM package to validate CSS
* [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) plugin for stylelint to validate CSS
* [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator)
* [Gulp plugin](https://github.com/csstree/gulp-csstree)
* [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree)
* [VS Code plugin](https://github.com/csstree/vscode-plugin)
* [Atom plugin](https://github.com/csstree/atom-plugin)
## Usage
Install with npm:
```
> npm install css-tree
```
Basic usage:
```js
var csstree = require('css-tree');
// parse CSS to AST
var ast = csstree.parse('.example { world: "!" }');
// traverse AST and modify it
csstree.walk(ast, function(node) {
if (node.type === 'ClassSelector' && node.name === 'example') {
node.name = 'hello';
}
});
// generate CSS from AST
console.log(csstree.generate(ast));
// .hello{world:"!"}
```
Syntax matching:
```js
// parse CSS to AST as a declaration value
var ast = csstree.parse('red 1px solid', { context: 'value' });
// match to syntax of `border` property
var matchResult = csstree.lexer.matchProperty('border', ast);
// check first value node is a <color>
console.log(matchResult.isType(ast.children.first(), 'color'));
// true
// get a type list matched to a node
console.log(matchResult.getTrace(ast.children.first()));
// [ { type: 'Property', name: 'border' },
// { type: 'Type', name: 'color' },
// { type: 'Type', name: 'named-color' },
// { type: 'Keyword', name: 'red' } ]
```
## Top level API
![API map](https://cdn.rawgit.com/csstree/csstree/1.0/docs/api-map.svg)
## License
MIT

View File

@@ -0,0 +1,103 @@
const mdnAtrules = require('mdn-data/css/at-rules.json');
const mdnProperties = require('mdn-data/css/properties.json');
const mdnSyntaxes = require('mdn-data/css/syntaxes.json');
const patch = require('./patch.json');
const extendSyntax = /^\s*\|\s*/;
function preprocessAtrules(dict) {
const result = Object.create(null);
for (const atruleName in dict) {
const atrule = dict[atruleName];
let descriptors = null;
if (atrule.descriptors) {
descriptors = Object.create(null);
for (const descriptor in atrule.descriptors) {
descriptors[descriptor] = atrule.descriptors[descriptor].syntax;
}
}
result[atruleName.substr(1)] = {
prelude: atrule.syntax.trim().match(/^@\S+\s+([^;\{]*)/)[1].trim() || null,
descriptors
};
}
return result;
}
function patchDictionary(dict, patchDict) {
const result = {};
// copy all syntaxes for an original dict
for (const key in dict) {
result[key] = dict[key].syntax || dict[key];
}
// apply a patch
for (const key in patchDict) {
if (key in dict) {
if (patchDict[key].syntax) {
result[key] = extendSyntax.test(patchDict[key].syntax)
? result[key] + ' ' + patchDict[key].syntax.trim()
: patchDict[key].syntax;
} else {
delete result[key];
}
} else {
if (patchDict[key].syntax) {
result[key] = patchDict[key].syntax.replace(extendSyntax, '');
}
}
}
return result;
}
function unpackSyntaxes(dict) {
const result = {};
for (const key in dict) {
result[key] = dict[key].syntax;
}
return result;
}
function patchAtrules(dict, patchDict) {
const result = {};
// copy all syntaxes for an original dict
for (const key in dict) {
const patchDescriptors = (patchDict[key] && patchDict[key].descriptors) || null;
result[key] = {
prelude: key in patchDict && 'prelude' in patchDict[key]
? patchDict[key].prelude
: dict[key].prelude || null,
descriptors: dict[key].descriptors
? patchDictionary(dict[key].descriptors, patchDescriptors || {})
: patchDescriptors && unpackSyntaxes(patchDescriptors)
};
}
// apply a patch
for (const key in patchDict) {
if (!hasOwnProperty.call(dict, key)) {
result[key] = {
prelude: patchDict[key].prelude || null,
descriptors: patchDict[key].descriptors && unpackSyntaxes(patchDict[key].descriptors)
};
}
}
return result;
}
module.exports = {
types: patchDictionary(mdnSyntaxes, patch.syntaxes),
atrules: patchAtrules(preprocessAtrules(mdnAtrules), patch.atrules),
properties: patchDictionary(mdnProperties, patch.properties)
};

View File

@@ -0,0 +1,721 @@
{
"atrules": {
"charset": {
"prelude": "<string>"
},
"font-face": {
"descriptors": {
"unicode-range": {
"comment": "replaces <unicode-range>, an old production name",
"syntax": "<urange>#"
}
}
}
},
"properties": {
"-moz-background-clip": {
"comment": "deprecated syntax in old Firefox, https://developer.mozilla.org/en/docs/Web/CSS/background-clip",
"syntax": "padding | border"
},
"-moz-border-radius-bottomleft": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius",
"syntax": "<'border-bottom-left-radius'>"
},
"-moz-border-radius-bottomright": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius",
"syntax": "<'border-bottom-right-radius'>"
},
"-moz-border-radius-topleft": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius",
"syntax": "<'border-top-left-radius'>"
},
"-moz-border-radius-topright": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius",
"syntax": "<'border-bottom-right-radius'>"
},
"-moz-control-character-visibility": {
"comment": "firefox specific keywords, https://bugzilla.mozilla.org/show_bug.cgi?id=947588",
"syntax": "visible | hidden"
},
"-moz-osx-font-smoothing": {
"comment": "misssed old syntax https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth",
"syntax": "auto | grayscale"
},
"-moz-user-select": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/user-select",
"syntax": "none | text | all | -moz-none"
},
"-ms-flex-align": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align",
"syntax": "start | end | center | baseline | stretch"
},
"-ms-flex-item-align": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align",
"syntax": "auto | start | end | center | baseline | stretch"
},
"-ms-flex-line-pack": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-line-pack",
"syntax": "start | end | center | justify | distribute | stretch"
},
"-ms-flex-negative": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-shrink'>"
},
"-ms-flex-pack": {
"comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-pack",
"syntax": "start | end | center | justify | distribute"
},
"-ms-flex-order": {
"comment": "misssed old syntax implemented in IE; https://msdn.microsoft.com/en-us/library/jj127303(v=vs.85).aspx",
"syntax": "<integer>"
},
"-ms-flex-positive": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-grow'>"
},
"-ms-flex-preferred-size": {
"comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation",
"syntax": "<'flex-basis'>"
},
"-ms-interpolation-mode": {
"comment": "https://msdn.microsoft.com/en-us/library/ff521095(v=vs.85).aspx",
"syntax": "nearest-neighbor | bicubic"
},
"-ms-grid-column-align": {
"comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466338.aspx",
"syntax": "start | end | center | stretch"
},
"-ms-grid-row-align": {
"comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466348.aspx",
"syntax": "start | end | center | stretch"
},
"-ms-hyphenate-limit-last": {
"comment": "misssed old syntax implemented in IE; https://www.w3.org/TR/css-text-4/#hyphenate-line-limits",
"syntax": "none | always | column | page | spread"
},
"-webkit-appearance": {
"comment": "webkit specific keywords",
"references": [
"http://css-infos.net/property/-webkit-appearance"
],
"syntax": "none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button"
},
"-webkit-background-clip": {
"comment": "https://developer.mozilla.org/en/docs/Web/CSS/background-clip",
"syntax": "[ <box> | border | padding | content | text ]#"
},
"-webkit-column-break-after": {
"comment": "added, http://help.dottoro.com/lcrthhhv.php",
"syntax": "always | auto | avoid"
},
"-webkit-column-break-before": {
"comment": "added, http://help.dottoro.com/lcxquvkf.php",
"syntax": "always | auto | avoid"
},
"-webkit-column-break-inside": {
"comment": "added, http://help.dottoro.com/lclhnthl.php",
"syntax": "always | auto | avoid"
},
"-webkit-font-smoothing": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth",
"syntax": "auto | none | antialiased | subpixel-antialiased"
},
"-webkit-mask-box-image": {
"comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-box-image",
"syntax": "[ <url> | <gradient> | none ] [ <length-percentage>{4} <-webkit-mask-box-repeat>{2} ]?"
},
"-webkit-print-color-adjust": {
"comment": "missed",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/-webkit-print-color-adjust"
],
"syntax": "economy | exact"
},
"-webkit-text-security": {
"comment": "missed; http://help.dottoro.com/lcbkewgt.php",
"syntax": "none | circle | disc | square"
},
"-webkit-user-drag": {
"comment": "missed; http://help.dottoro.com/lcbixvwm.php",
"syntax": "none | element | auto"
},
"-webkit-user-select": {
"comment": "auto is supported by old webkit, https://developer.mozilla.org/en-US/docs/Web/CSS/user-select",
"syntax": "auto | none | text | all"
},
"alignment-baseline": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#AlignmentBaselineProperty"
],
"syntax": "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical"
},
"baseline-shift": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#BaselineShiftProperty"
],
"syntax": "baseline | sub | super | <svg-length>"
},
"behavior": {
"comment": "added old IE property https://msdn.microsoft.com/en-us/library/ms530723(v=vs.85).aspx",
"syntax": "<url>+"
},
"clip-rule": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/masking.html#ClipRuleProperty"
],
"syntax": "nonzero | evenodd"
},
"cue": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'cue-before'> <'cue-after'>?"
},
"cue-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<url> <decibel>? | none"
},
"cue-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<url> <decibel>? | none"
},
"cursor": {
"comment": "added legacy keywords: hand, -webkit-grab. -webkit-grabbing, -webkit-zoom-in, -webkit-zoom-out, -moz-grab, -moz-grabbing, -moz-zoom-in, -moz-zoom-out",
"references": [
"https://www.sitepoint.com/css3-cursor-styles/"
],
"syntax": "[ [ <url> [ <x> <y> ]? , ]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing | hand | -webkit-grab | -webkit-grabbing | -webkit-zoom-in | -webkit-zoom-out | -moz-grab | -moz-grabbing | -moz-zoom-in | -moz-zoom-out ] ]"
},
"display": {
"comment": "extended with -ms-flexbox",
"syntax": "| <-non-standard-display>"
},
"position": {
"comment": "extended with -webkit-sticky",
"syntax": "| -webkit-sticky"
},
"dominant-baseline": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#DominantBaselineProperty"
],
"syntax": "auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge"
},
"image-rendering": {
"comment": "extended with <-non-standard-image-rendering>, added SVG keywords optimizeSpeed and optimizeQuality",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/image-rendering",
"https://www.w3.org/TR/SVG/painting.html#ImageRenderingProperty"
],
"syntax": "| optimizeSpeed | optimizeQuality | <-non-standard-image-rendering>"
},
"fill": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "<paint>"
},
"fill-opacity": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "<number-zero-one>"
},
"fill-rule": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#FillProperty"
],
"syntax": "nonzero | evenodd"
},
"filter": {
"comment": "extend with IE legacy syntaxes",
"syntax": "| <-ms-filter-function-list>"
},
"glyph-orientation-horizontal": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#GlyphOrientationHorizontalProperty"
],
"syntax": "<angle>"
},
"glyph-orientation-vertical": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#GlyphOrientationVerticalProperty"
],
"syntax": "<angle>"
},
"kerning": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#KerningProperty"
],
"syntax": "auto | <svg-length>"
},
"letter-spacing": {
"comment": "fix syntax <length> -> <length-percentage>",
"references": [
"https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing"
],
"syntax": "normal | <length-percentage>"
},
"marker": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-end": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-mid": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"marker-start": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#MarkerProperties"
],
"syntax": "none | <url>"
},
"max-width": {
"comment": "fix auto -> none (https://github.com/mdn/data/pull/431); extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/max-width",
"syntax": "none | <length-percentage> | min-content | max-content | fit-content(<length-percentage>) | <-non-standard-width>"
},
"width": {
"comment": "per spec fit-content should be a function, however browsers are supporting it as a keyword (https://github.com/csstree/stylelint-validator/issues/29)",
"syntax": "| fit-content | -moz-fit-content | -webkit-fit-content"
},
"min-width": {
"comment": "extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/width",
"syntax": "auto | <length-percentage> | min-content | max-content | fit-content(<length-percentage>) | <-non-standard-width>"
},
"overflow": {
"comment": "extend by vendor keywords https://developer.mozilla.org/en-US/docs/Web/CSS/overflow",
"syntax": "| <-non-standard-overflow>"
},
"pause": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'pause-before'> <'pause-after'>?"
},
"pause-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"pause-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"rest": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<'rest-before'> <'rest-after'>?"
},
"rest-after": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"rest-before": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<time> | none | x-weak | weak | medium | strong | x-strong"
},
"shape-rendering": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#ShapeRenderingPropert"
],
"syntax": "auto | optimizeSpeed | crispEdges | geometricPrecision"
},
"src": {
"comment": "added @font-face's src property https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src",
"syntax": "[ <url> [ format( <string># ) ]? | local( <family-name> ) ]#"
},
"speak": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "auto | none | normal"
},
"speak-as": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "normal | spell-out || digits || [ literal-punctuation | no-punctuation ]"
},
"stroke": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<paint>"
},
"stroke-dasharray": {
"comment": "added SVG property; a list of comma and/or white space separated <length>s and <percentage>s",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "none | [ <svg-length>+ ]#"
},
"stroke-dashoffset": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<svg-length>"
},
"stroke-linecap": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "butt | round | square"
},
"stroke-linejoin": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "miter | round | bevel"
},
"stroke-miterlimit": {
"comment": "added SVG property (<miterlimit> = <number-one-or-greater>) ",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<number-one-or-greater>"
},
"stroke-opacity": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<number-zero-one>"
},
"stroke-width": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/painting.html#StrokeProperties"
],
"syntax": "<svg-length>"
},
"text-anchor": {
"comment": "added SVG property",
"references": [
"https://www.w3.org/TR/SVG/text.html#TextAlignmentProperties"
],
"syntax": "start | middle | end"
},
"unicode-bidi": {
"comment": "added prefixed keywords https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi",
"syntax": "| -moz-isolate | -moz-isolate-override | -moz-plaintext | -webkit-isolate | -webkit-isolate-override | -webkit-plaintext"
},
"unicode-range": {
"comment": "added missed property https://developer.mozilla.org/en-US/docs/Web/CSS/%40font-face/unicode-range",
"syntax": "<urange>#"
},
"voice-balance": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<number> | left | center | right | leftwards | rightwards"
},
"voice-duration": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "auto | <time>"
},
"voice-family": {
"comment": "<name> -> <family-name>, https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "[ [ <family-name> | <generic-voice> ] , ]* [ <family-name> | <generic-voice> ] | preserve"
},
"voice-pitch": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<frequency> && absolute | [ [ x-low | low | medium | high | x-high ] || [ <frequency> | <semitones> | <percentage> ] ]"
},
"voice-range": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "<frequency> && absolute | [ [ x-low | low | medium | high | x-high ] || [ <frequency> | <semitones> | <percentage> ] ]"
},
"voice-rate": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "[ normal | x-slow | slow | medium | fast | x-fast ] || <percentage>"
},
"voice-stress": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "normal | strong | moderate | none | reduced"
},
"voice-volume": {
"comment": "https://www.w3.org/TR/css3-speech/#property-index",
"syntax": "silent | [ [ x-soft | soft | medium | loud | x-loud ] || <decibel> ]"
},
"writing-mode": {
"comment": "extend with SVG keywords",
"syntax": "| <svg-writing-mode>"
}
},
"syntaxes": {
"-legacy-gradient": {
"comment": "added collection of legacy gradient syntaxes",
"syntax": "<-webkit-gradient()> | <-legacy-linear-gradient> | <-legacy-repeating-linear-gradient> | <-legacy-radial-gradient> | <-legacy-repeating-radial-gradient>"
},
"-legacy-linear-gradient": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "-moz-linear-gradient( <-legacy-linear-gradient-arguments> ) | -webkit-linear-gradient( <-legacy-linear-gradient-arguments> ) | -o-linear-gradient( <-legacy-linear-gradient-arguments> )"
},
"-legacy-repeating-linear-gradient": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "-moz-repeating-linear-gradient( <-legacy-linear-gradient-arguments> ) | -webkit-repeating-linear-gradient( <-legacy-linear-gradient-arguments> ) | -o-repeating-linear-gradient( <-legacy-linear-gradient-arguments> )"
},
"-legacy-linear-gradient-arguments": {
"comment": "like standard syntax but w/o `to` keyword https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient",
"syntax": "[ <angle> | <side-or-corner> ]? , <color-stop-list>"
},
"-legacy-radial-gradient": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "-moz-radial-gradient( <-legacy-radial-gradient-arguments> ) | -webkit-radial-gradient( <-legacy-radial-gradient-arguments> ) | -o-radial-gradient( <-legacy-radial-gradient-arguments> )"
},
"-legacy-repeating-radial-gradient": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "-moz-repeating-radial-gradient( <-legacy-radial-gradient-arguments> ) | -webkit-repeating-radial-gradient( <-legacy-radial-gradient-arguments> ) | -o-repeating-radial-gradient( <-legacy-radial-gradient-arguments> )"
},
"-legacy-radial-gradient-arguments": {
"comment": "deprecated syntax that implemented by some browsers https://www.w3.org/TR/2011/WD-css3-images-20110908/#radial-gradients",
"syntax": "[ <position> , ]? [ [ [ <-legacy-radial-gradient-shape> || <-legacy-radial-gradient-size> ] | [ <length> | <percentage> ]{2} ] , ]? <color-stop-list>"
},
"-legacy-radial-gradient-size": {
"comment": "before a standard it contains 2 extra keywords (`contain` and `cover`) https://www.w3.org/TR/2011/WD-css3-images-20110908/#ltsize",
"syntax": "closest-side | closest-corner | farthest-side | farthest-corner | contain | cover"
},
"-legacy-radial-gradient-shape": {
"comment": "define to double sure it doesn't extends in future https://www.w3.org/TR/2011/WD-css3-images-20110908/#ltshape",
"syntax": "circle | ellipse"
},
"-non-standard-font": {
"comment": "non standard fonts",
"references": [
"https://webkit.org/blog/3709/using-the-system-font-in-web-content/"
],
"syntax": "-apple-system-body | -apple-system-headline | -apple-system-subheadline | -apple-system-caption1 | -apple-system-caption2 | -apple-system-footnote | -apple-system-short-body | -apple-system-short-headline | -apple-system-short-subheadline | -apple-system-short-caption1 | -apple-system-short-footnote | -apple-system-tall-body"
},
"-non-standard-color": {
"comment": "non standard colors",
"references": [
"http://cssdot.ru/%D0%A1%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D1%87%D0%BD%D0%B8%D0%BA_CSS/color-i305.html",
"https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Mozilla_Color_Preference_Extensions"
],
"syntax": "-moz-ButtonDefault | -moz-ButtonHoverFace | -moz-ButtonHoverText | -moz-CellHighlight | -moz-CellHighlightText | -moz-Combobox | -moz-ComboboxText | -moz-Dialog | -moz-DialogText | -moz-dragtargetzone | -moz-EvenTreeRow | -moz-Field | -moz-FieldText | -moz-html-CellHighlight | -moz-html-CellHighlightText | -moz-mac-accentdarkestshadow | -moz-mac-accentdarkshadow | -moz-mac-accentface | -moz-mac-accentlightesthighlight | -moz-mac-accentlightshadow | -moz-mac-accentregularhighlight | -moz-mac-accentregularshadow | -moz-mac-chrome-active | -moz-mac-chrome-inactive | -moz-mac-focusring | -moz-mac-menuselect | -moz-mac-menushadow | -moz-mac-menutextselect | -moz-MenuHover | -moz-MenuHoverText | -moz-MenuBarText | -moz-MenuBarHoverText | -moz-nativehyperlinktext | -moz-OddTreeRow | -moz-win-communicationstext | -moz-win-mediatext | -moz-activehyperlinktext | -moz-default-background-color | -moz-default-color | -moz-hyperlinktext | -moz-visitedhyperlinktext | -webkit-activelink | -webkit-focus-ring-color | -webkit-link | -webkit-text"
},
"-non-standard-image-rendering": {
"comment": "non-standard keywords http://phrogz.net/tmp/canvas_image_zoom.html",
"syntax": "optimize-contrast | -moz-crisp-edges | -o-crisp-edges | -webkit-optimize-contrast"
},
"-non-standard-overflow": {
"comment": "non-standard keywords https://developer.mozilla.org/en-US/docs/Web/CSS/overflow",
"syntax": "-moz-scrollbars-none | -moz-scrollbars-horizontal | -moz-scrollbars-vertical | -moz-hidden-unscrollable"
},
"-non-standard-width": {
"comment": "non-standard keywords https://developer.mozilla.org/en-US/docs/Web/CSS/width",
"syntax": "fill-available | min-intrinsic | intrinsic | -moz-available | -moz-fit-content | -moz-min-content | -moz-max-content | -webkit-min-content | -webkit-max-content"
},
"-webkit-gradient()": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/ - TODO: simplify when after match algorithm improvement ( [, point, radius | , point] -> [, radius]? , point )",
"syntax": "-webkit-gradient( <-webkit-gradient-type>, <-webkit-gradient-point> [, <-webkit-gradient-point> | , <-webkit-gradient-radius>, <-webkit-gradient-point> ] [, <-webkit-gradient-radius>]? [, <-webkit-gradient-color-stop>]* )"
},
"-webkit-gradient-color-stop": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "from( <color> ) | color-stop( [ <number-zero-one> | <percentage> ] , <color> ) | to( <color> )"
},
"-webkit-gradient-point": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "[ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]"
},
"-webkit-gradient-radius": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "<length> | <percentage>"
},
"-webkit-gradient-type": {
"comment": "first Apple proposal gradient syntax https://webkit.org/blog/175/introducing-css-gradients/",
"syntax": "linear | radial"
},
"-webkit-mask-box-repeat": {
"comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-box-image",
"syntax": "repeat | stretch | round"
},
"-webkit-mask-clip-style": {
"comment": "missed; there is no enough information about `-webkit-mask-clip` property, but looks like all those keywords are working",
"syntax": "border | border-box | padding | padding-box | content | content-box | text"
},
"-ms-filter-function-list": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-filter",
"syntax": "<-ms-filter-function>+"
},
"-ms-filter-function": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-filter",
"syntax": "<-ms-filter-function-progid> | <-ms-filter-function-legacy>"
},
"-ms-filter-function-progid": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-filter",
"syntax": "'progid:' [ <ident-token> '.' ]* [ <ident-token> | <function-token> <any-value>? ) ]"
},
"-ms-filter-function-legacy": {
"comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-filter",
"syntax": "<ident-token> | <function-token> <any-value>? )"
},
"-ms-filter": {
"syntax": "<string>"
},
"age": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "child | young | old"
},
"attr-name": {
"syntax": "<wq-name>"
},
"attr-fallback": {
"syntax": "<any-value>"
},
"border-radius": {
"comment": "missed, https://drafts.csswg.org/css-backgrounds-3/#the-border-radius",
"syntax": "<length-percentage>{1,2}"
},
"bottom": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"content-list": {
"comment": "missed -> https://drafts.csswg.org/css-content/#typedef-content-list (document-url, <target> and leader() is omitted util stabilization)",
"syntax": "[ <string> | contents | <image> | <quote> | <target> | <leader()> | <attr()> | counter( <ident>, <'list-style-type'>? ) ]+"
},
"element()": {
"comment": "https://drafts.csswg.org/css-gcpm/#element-syntax & https://drafts.csswg.org/css-images-4/#element-notation",
"syntax": "element( <custom-ident> , [ first | start | last | first-except ]? ) | element( <id-selector> )"
},
"generic-voice": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "[ <age>? <gender> <integer>? ]"
},
"gender": {
"comment": "https://www.w3.org/TR/css3-speech/#voice-family",
"syntax": "male | female | neutral"
},
"generic-family": {
"comment": "added -apple-system",
"references": [
"https://webkit.org/blog/3709/using-the-system-font-in-web-content/"
],
"syntax": "| -apple-system"
},
"gradient": {
"comment": "added legacy syntaxes support",
"syntax": "| <-legacy-gradient>"
},
"left": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"mask-image": {
"comment": "missed; https://drafts.fxtf.org/css-masking-1/#the-mask-image",
"syntax": "<mask-reference>#"
},
"name-repeat": {
"comment": "missed, and looks like obsolete, keep it as is since other property syntaxes should be changed too; https://www.w3.org/TR/2015/WD-css-grid-1-20150917/#typedef-name-repeat",
"syntax": "repeat( [ <positive-integer> | auto-fill ], <line-names>+)"
},
"named-color": {
"comment": "added non standard color names",
"syntax": "| <-non-standard-color>"
},
"paint": {
"comment": "used by SVG https://www.w3.org/TR/SVG/painting.html#SpecifyingPaint",
"syntax": "none | <color> | <url> [ none | <color> ]? | context-fill | context-stroke"
},
"page-size": {
"comment": "https://www.w3.org/TR/css-page-3/#typedef-page-size-page-size",
"syntax": "A5 | A4 | A3 | B5 | B4 | JIS-B5 | JIS-B4 | letter | legal | ledger"
},
"ratio": {
"comment": "missed, https://drafts.csswg.org/mediaqueries-4/#typedef-ratio",
"syntax": "<integer> / <integer>"
},
"right": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"shape": {
"comment": "missed spaces in function body and add backwards compatible syntax",
"syntax": "rect( <top>, <right>, <bottom>, <left> ) | rect( <top> <right> <bottom> <left> )"
},
"svg-length": {
"comment": "All coordinates and lengths in SVG can be specified with or without a unit identifier",
"references": [
"https://www.w3.org/TR/SVG11/coords.html#Units"
],
"syntax": "<percentage> | <length> | <number>"
},
"svg-writing-mode": {
"comment": "SVG specific keywords (deprecated for CSS)",
"references": [
"https://developer.mozilla.org/en/docs/Web/CSS/writing-mode",
"https://www.w3.org/TR/SVG/text.html#WritingModeProperty"
],
"syntax": "lr-tb | rl-tb | tb-rl | lr | rl | tb"
},
"top": {
"comment": "missed; not sure we should add it, but no others except `shape` is using it so it's ok for now; https://drafts.fxtf.org/css-masking-1/#funcdef-clip-rect",
"syntax": "<length> | auto"
},
"track-group": {
"comment": "used by old grid-columns and grid-rows syntax v0",
"syntax": "'(' [ <string>* <track-minmax> <string>* ]+ ')' [ '[' <positive-integer> ']' ]? | <track-minmax>"
},
"track-list-v0": {
"comment": "used by old grid-columns and grid-rows syntax v0",
"syntax": "[ <string>* <track-group> <string>* ]+ | none"
},
"track-minmax": {
"comment": "used by old grid-columns and grid-rows syntax v0",
"syntax": "minmax( <track-breadth> , <track-breadth> ) | auto | <track-breadth> | fit-content"
},
"x": {
"comment": "missed; not sure we should add it, but no others except `cursor` is using it so it's ok for now; https://drafts.csswg.org/css-ui-3/#cursor",
"syntax": "<number>"
},
"y": {
"comment": "missed; not sure we should add it, but no others except `cursor` is using so it's ok for now; https://drafts.csswg.org/css-ui-3/#cursor",
"syntax": "<number>"
},
"declaration": {
"comment": "missed, restored by https://drafts.csswg.org/css-syntax",
"syntax": "<ident-token> : <declaration-value>? [ '!' important ]?"
},
"declaration-list": {
"comment": "missed, restored by https://drafts.csswg.org/css-syntax",
"syntax": "[ <declaration>? ';' ]* <declaration>?"
},
"url": {
"comment": "https://drafts.csswg.org/css-values-4/#urls",
"syntax": "url( <string> <url-modifier>* ) | <url-token>"
},
"url-modifier": {
"comment": "https://drafts.csswg.org/css-values-4/#typedef-url-modifier",
"syntax": "<ident> | <function-token> <any-value> )"
},
"number-zero-one": {
"syntax": "<number [0,1]>"
},
"number-one-or-greater": {
"syntax": "<number [1,∞]>"
},
"positive-integer": {
"syntax": "<integer [0,∞]>"
},
"-non-standard-display": {
"syntax": "-ms-inline-flexbox | -ms-grid | -ms-inline-grid | -webkit-flex | -webkit-inline-flex | -webkit-box | -webkit-inline-box | -moz-inline-stack | -moz-box | -moz-inline-box"
}
}
}

View File

@@ -0,0 +1,60 @@
{
"name": "css-tree",
"version": "1.1.3",
"description": "A tool set for CSS: fast detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations",
"author": "Roman Dvornov <rdvornov@gmail.com> (https://github.com/lahmatiy)",
"license": "MIT",
"repository": "csstree/csstree",
"keywords": [
"css",
"ast",
"tokenizer",
"parser",
"walker",
"lexer",
"generator",
"utils",
"syntax",
"validation"
],
"main": "lib/index.js",
"unpkg": "dist/csstree.min.js",
"jsdelivr": "dist/csstree.min.js",
"scripts": {
"build": "rollup --config",
"lint": "eslint data lib scripts test && node scripts/review-syntax-patch --lint && node scripts/update-docs --lint",
"lint-and-test": "npm run lint && npm test",
"update:docs": "node scripts/update-docs",
"review:syntax-patch": "node scripts/review-syntax-patch",
"test": "mocha --reporter progress",
"coverage": "nyc npm test",
"travis": "nyc npm run lint-and-test && npm run coveralls",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"prepublishOnly": "npm run build",
"hydrogen": "node --trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces --redirect-code-traces-to=code.asm --trace_hydrogen_file=code.cfg --print-opt-code bin/parse --stat -o /dev/null"
},
"dependencies": {
"mdn-data": "2.0.14",
"source-map": "^0.6.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^11.0.2",
"@rollup/plugin-json": "^4.0.2",
"@rollup/plugin-node-resolve": "^7.1.1",
"coveralls": "^3.0.9",
"eslint": "^6.8.0",
"json-to-ast": "^2.1.0",
"mocha": "^6.2.3",
"nyc": "^14.1.1",
"rollup": "^1.32.1",
"rollup-plugin-terser": "^5.3.0"
},
"engines": {
"node": ">=8.0.0"
},
"files": [
"data",
"dist",
"lib"
]
}

View File

@@ -0,0 +1,116 @@
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>

View File

@@ -0,0 +1,56 @@
# MDN data
[https://github.com/mdn/data](https://github.com/mdn/data)
Maintained by the [MDN team at Mozilla](https://wiki.mozilla.org/MDN).
This repository contains general data for Web technologies.
This data is used in MDN documentation, to build
[information boxes](https://developer.mozilla.org/en-US/docs/Web/CSS/background)
or [sidebar navigation](https://developer.mozilla.org/en-US/docs/Web/API/Window).
External tools have started to make use of this data as well.
For example, the [CSSTree](https://github.com/csstree/csstree/) CSS parser.
[![NPM version](https://img.shields.io/npm/v/mdn-data.svg)](https://www.npmjs.com/package/mdn-data)
[![Build Status](https://travis-ci.org/mdn/data.svg?branch=master)](https://travis-ci.org/mdn/data)
## Repository contents
There's a top-level directory for each broad area covered: for example, "api",
"css", "svg". Inside each of these directories is one or more
JSON files containing the data.
### api
Contains data about Web APIs:
* API inheritance (interface inheritance and mixin implementations)
### css
Contains data about:
* CSS at-rules
* CSS properties
* CSS selectors
* CSS syntaxes
* CSS types
* CSS units
Read more about [CSS data](https://github.com/mdn/data/blob/master/css/readme.md) and the format of the files.
### l10n
The l10n folder contains localization strings that are used in the various
json files throughout this repository.
## Problems?
If you find a problem, please [file an issue](https://github.com/mdn/data/issues/new).
## Contributing
We're very happy to accept contributions to this data. Please familiarize yourself
with the schema for the data you're editing, and send us a pull request. See also the [Contributing file](https://github.com/mdn/data/blob/master/CONTRIBUTING.md) for more information.
## See also
* [https://github.com/mdn/browser-compat-data](https://github.com/mdn/browser-compat-data)
for compatibility data for Web technologies.

View File

@@ -0,0 +1,3 @@
module.exports = {
inheritance: require('./inheritance'),
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
{
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"inherits": {
"oneOf": [
{
"type": "null"
},
{
"type": "string",
"minLength": 1
}
]
},
"implements": {
"minItems": 0,
"uniqueItems": true,
"items": {
"type": "string"
}
}
},
"required": [
"inherits",
"implements"
]
}
}

View File

@@ -0,0 +1,560 @@
{
"@charset": {
"syntax": "@charset \"<charset>\";",
"groups": [
"CSS Charsets"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@charset"
},
"@counter-style": {
"syntax": "@counter-style <counter-style-name> {\n [ system: <counter-system>; ] ||\n [ symbols: <counter-symbols>; ] ||\n [ additive-symbols: <additive-symbols>; ] ||\n [ negative: <negative-symbol>; ] ||\n [ prefix: <prefix>; ] ||\n [ suffix: <suffix>; ] ||\n [ range: <range>; ] ||\n [ pad: <padding>; ] ||\n [ speak-as: <speak-as>; ] ||\n [ fallback: <counter-style-name>; ]\n}",
"interfaces": [
"CSSCounterStyleRule"
],
"groups": [
"CSS Counter Styles"
],
"descriptors": {
"additive-symbols": {
"syntax": "[ <integer> && <symbol> ]#",
"media": "all",
"initial": "n/a (required)",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"fallback": {
"syntax": "<counter-style-name>",
"media": "all",
"initial": "decimal",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"negative": {
"syntax": "<symbol> <symbol>?",
"media": "all",
"initial": "\"-\" hyphen-minus",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"pad": {
"syntax": "<integer> && <symbol>",
"media": "all",
"initial": "0 \"\"",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"prefix": {
"syntax": "<symbol>",
"media": "all",
"initial": "\"\"",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"range": {
"syntax": "[ [ <integer> | infinite ]{2} ]# | auto",
"media": "all",
"initial": "auto",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"speak-as": {
"syntax": "auto | bullets | numbers | words | spell-out | <counter-style-name>",
"media": "all",
"initial": "auto",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"suffix": {
"syntax": "<symbol>",
"media": "all",
"initial": "\". \"",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"symbols": {
"syntax": "<symbol>+",
"media": "all",
"initial": "n/a (required)",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"system": {
"syntax": "cyclic | numeric | alphabetic | symbolic | additive | [ fixed <integer>? ] | [ extends <counter-style-name> ]",
"media": "all",
"initial": "symbolic",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
}
},
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@counter-style"
},
"@document": {
"syntax": "@document [ <url> | url-prefix(<string>) | domain(<string>) | media-document(<string>) | regexp(<string>) ]# {\n <group-rule-body>\n}",
"interfaces": [
"CSSGroupingRule",
"CSSConditionRule"
],
"groups": [
"CSS Conditional Rules"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@document"
},
"@font-face": {
"syntax": "@font-face {\n [ font-family: <family-name>; ] ||\n [ src: <src>; ] ||\n [ unicode-range: <unicode-range>; ] ||\n [ font-variant: <font-variant>; ] ||\n [ font-feature-settings: <font-feature-settings>; ] ||\n [ font-variation-settings: <font-variation-settings>; ] ||\n [ font-stretch: <font-stretch>; ] ||\n [ font-weight: <font-weight>; ] ||\n [ font-style: <font-style>; ]\n}",
"interfaces": [
"CSSFontFaceRule"
],
"groups": [
"CSS Fonts"
],
"descriptors": {
"font-display": {
"syntax": "[ auto | block | swap | fallback | optional ]",
"media": "visual",
"percentages": "no",
"initial": "auto",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "experimental"
},
"font-family": {
"syntax": "<family-name>",
"media": "all",
"initial": "n/a (required)",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"font-feature-settings": {
"syntax": "normal | <feature-tag-value>#",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"font-variation-settings": {
"syntax": "normal | [ <string> <number> ]#",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"font-stretch": {
"syntax": "<font-stretch-absolute>{1,2}",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"font-style": {
"syntax": "normal | italic | oblique <angle>{0,2}",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"font-weight": {
"syntax": "<font-weight-absolute>{1,2}",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"font-variant": {
"syntax": "normal | none | [ <common-lig-values> || <discretionary-lig-values> || <historical-lig-values> || <contextual-alt-values> || stylistic(<feature-value-name>) || historical-forms || styleset(<feature-value-name>#) || character-variant(<feature-value-name>#) || swash(<feature-value-name>) || ornaments(<feature-value-name>) || annotation(<feature-value-name>) || [ small-caps | all-small-caps | petite-caps | all-petite-caps | unicase | titling-caps ] || <numeric-figure-values> || <numeric-spacing-values> || <numeric-fraction-values> || ordinal || slashed-zero || <east-asian-variant-values> || <east-asian-width-values> || ruby ]",
"media": "all",
"initial": "normal",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"src": {
"syntax": "[ <url> [ format( <string># ) ]? | local( <family-name> ) ]#",
"media": "all",
"initial": "n/a (required)",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"unicode-range": {
"syntax": "<unicode-range>#",
"media": "all",
"initial": "U+0-10FFFF",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
}
},
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@font-face"
},
"@font-feature-values": {
"syntax": "@font-feature-values <family-name># {\n <feature-value-block-list>\n}",
"interfaces": [
"CSSFontFeatureValuesRule"
],
"groups": [
"CSS Fonts"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@font-feature-values"
},
"@import": {
"syntax": "@import [ <string> | <url> ] [ <media-query-list> ]?;",
"groups": [
"Media Queries"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@import"
},
"@keyframes": {
"syntax": "@keyframes <keyframes-name> {\n <keyframe-block-list>\n}",
"interfaces": [
"CSSKeyframeRule",
"CSSKeyframesRule"
],
"groups": [
"CSS Animations"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@keyframes"
},
"@media": {
"syntax": "@media <media-query-list> {\n <group-rule-body>\n}",
"interfaces": [
"CSSGroupingRule",
"CSSConditionRule",
"CSSMediaRule",
"CSSCustomMediaRule"
],
"groups": [
"CSS Conditional Rules",
"Media Queries"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@media"
},
"@namespace": {
"syntax": "@namespace <namespace-prefix>? [ <string> | <url> ];",
"groups": [
"CSS Namespaces"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@namespace"
},
"@page": {
"syntax": "@page <page-selector-list> {\n <page-body>\n}",
"interfaces": [
"CSSPageRule"
],
"groups": [
"CSS Pages"
],
"descriptors": {
"bleed": {
"syntax": "auto | <length>",
"media": [
"visual",
"paged"
],
"initial": "auto",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"marks": {
"syntax": "none | [ crop || cross ]",
"media": [
"visual",
"paged"
],
"initial": "none",
"percentages": "no",
"computed": "asSpecified",
"order": "orderOfAppearance",
"status": "standard"
},
"size": {
"syntax": "<length>{1,2} | auto | [ <page-size> || [ portrait | landscape ] ]",
"media": [
"visual",
"paged"
],
"initial": "auto",
"percentages": "no",
"computed": "asSpecifiedRelativeToAbsoluteLengths",
"order": "orderOfAppearance",
"status": "standard"
}
},
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@page"
},
"@property": {
"syntax": "@property <custom-property-name> {\n <declaration-list>\n}",
"interfaces": [
"CSS",
"CSSPropertyRule"
],
"groups": [
"CSS Houdini"
],
"descriptors": {
"syntax": {
"syntax": "<string>",
"media": "all",
"percentages": "no",
"initial": "n/a (required)",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "experimental"
},
"inherits": {
"syntax": "true | false",
"media": "all",
"percentages": "no",
"initial": "auto",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "experimental"
},
"initial-value": {
"syntax": "<string>",
"media": "all",
"initial": "n/a (required)",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "experimental"
}
},
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@property"
},
"@supports": {
"syntax": "@supports <supports-condition> {\n <group-rule-body>\n}",
"interfaces": [
"CSSGroupingRule",
"CSSConditionRule",
"CSSSupportsRule"
],
"groups": [
"CSS Conditional Rules"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@supports"
},
"@viewport": {
"syntax": "@viewport {\n <group-rule-body>\n}",
"interfaces": [
"CSSViewportRule"
],
"groups": [
"CSS Device Adaptation"
],
"descriptors": {
"height": {
"syntax": "<viewport-length>{1,2}",
"media": [
"visual",
"continuous"
],
"initial": [
"min-height",
"max-height"
],
"percentages": [
"min-height",
"max-height"
],
"computed": [
"min-height",
"max-height"
],
"order": "orderOfAppearance",
"status": "standard"
},
"max-height": {
"syntax": "<viewport-length>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "referToHeightOfInitialViewport",
"computed": "lengthAbsolutePercentageAsSpecifiedOtherwiseAuto",
"order": "uniqueOrder",
"status": "standard"
},
"max-width": {
"syntax": "<viewport-length>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "referToWidthOfInitialViewport",
"computed": "lengthAbsolutePercentageAsSpecifiedOtherwiseAuto",
"order": "uniqueOrder",
"status": "standard"
},
"max-zoom": {
"syntax": "auto | <number> | <percentage>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "the zoom factor itself",
"computed": "autoNonNegativeOrPercentage",
"order": "uniqueOrder",
"status": "standard"
},
"min-height": {
"syntax": "<viewport-length>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "referToHeightOfInitialViewport",
"computed": "lengthAbsolutePercentageAsSpecifiedOtherwiseAuto",
"order": "uniqueOrder",
"status": "standard"
},
"min-width": {
"syntax": "<viewport-length>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "referToWidthOfInitialViewport",
"computed": "lengthAbsolutePercentageAsSpecifiedOtherwiseAuto",
"order": "uniqueOrder",
"status": "standard"
},
"min-zoom": {
"syntax": "auto | <number> | <percentage>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "the zoom factor itself",
"computed": "autoNonNegativeOrPercentage",
"order": "uniqueOrder",
"status": "standard"
},
"orientation": {
"syntax": "auto | portrait | landscape",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "referToSizeOfBoundingBox",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"user-zoom": {
"syntax": "zoom | fixed",
"media": [
"visual",
"continuous"
],
"initial": "zoom",
"percentages": "referToSizeOfBoundingBox",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"viewport-fit": {
"syntax": "auto | contain | cover",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "no",
"computed": "asSpecified",
"order": "uniqueOrder",
"status": "standard"
},
"width": {
"syntax": "<viewport-length>{1,2}",
"media": [
"visual",
"continuous"
],
"initial": [
"min-width",
"max-width"
],
"percentages": [
"min-width",
"max-width"
],
"computed": [
"min-width",
"max-width"
],
"order": "orderOfAppearance",
"status": "standard"
},
"zoom": {
"syntax": "auto | <number> | <percentage>",
"media": [
"visual",
"continuous"
],
"initial": "auto",
"percentages": "the zoom factor itself",
"computed": "autoNonNegativeOrPercentage",
"order": "uniqueOrder",
"status": "standard"
}
},
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/@viewport"
}
}

View File

@@ -0,0 +1,132 @@
{
"definitions": {
"stringOrPropertyList": {
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "string",
"property-reference": {
"comment": "property-reference is an extension to the JSON schema validator. Here it jumps 3 levels up in the hierarchy and tests if a value is an existing key in descriptors. See test/validate-schema.js for implementation details.",
"$data": "3"
}
}
}
]
}
},
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"syntax": {
"type": "string"
},
"interfaces": {
"type": "array",
"items": {
"type": "string"
}
},
"groups": {
"type": "array",
"minitems": 1,
"uniqueItems": true,
"items": {
"$ref": "definitions.json#/groupList"
}
},
"descriptors": {
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"syntax": {
"type": "string"
},
"media": {
"oneOf": [
{
"type": "string",
"enum": [
"all",
"continuous",
"paged",
"visual"
]
},
{
"type": "array",
"minItems": 2,
"uniqueItems": true,
"items": {
"type": "string",
"enum": [
"continuous",
"paged",
"visual"
]
}
}
]
},
"initial": {
"$ref": "#/definitions/stringOrPropertyList"
},
"percentages": {
"$ref": "#/definitions/stringOrPropertyList"
},
"computed": {
"$ref": "#/definitions/stringOrPropertyList"
},
"order": {
"enum": [
"orderOfAppearance",
"uniqueOrder"
]
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental"
]
}
},
"required": [
"syntax",
"media",
"initial",
"percentages",
"computed",
"order",
"status"
]
}
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental"
]
},
"mdn_url": {
"type": "string",
"pattern": "^https://developer.mozilla.org/docs/Web/CSS/"
}
},
"required": [
"syntax",
"groups",
"status"
]
}
}

View File

@@ -0,0 +1,77 @@
{
"groupList": {
"enum": [
"Basic Selectors",
"Combinators",
"Compositing and Blending",
"CSS Angles",
"CSS Animations",
"CSS Backgrounds and Borders",
"CSS Box Model",
"CSS Box Alignment",
"CSS Break",
"CSS Charsets",
"CSS Color",
"CSS Columns",
"CSS Conditional Rules",
"CSS Containment",
"CSS Counter Styles",
"CSS Device Adaptation",
"CSS Display",
"CSS Flexible Box Layout",
"CSS Flexible Lengths",
"CSS Fonts",
"CSS Fragmentation",
"CSS Frequencies",
"CSS Generated Content",
"CSS Grid Layout",
"CSS Houdini",
"CSS Images",
"CSS Inline",
"CSS Lengths",
"CSS Lists and Counters",
"CSS Logical Properties",
"CSS Masking",
"CSS Miscellaneous",
"CSS Motion Path",
"CSS Namespaces",
"CSS Overflow",
"CSS Pages",
"CSS Positioning",
"CSS Regions",
"CSS Resolutions",
"CSS Ruby",
"CSS Scroll Anchoring",
"CSS Scrollbars",
"CSS Scroll Snap",
"CSS Shadow Parts",
"CSS Shapes",
"CSS Speech",
"CSS Table",
"CSS Text",
"CSS Text Decoration",
"CSS Times",
"CSS Transforms",
"CSS Transitions",
"CSS Types",
"CSS Units",
"CSS Basic User Interface",
"CSS Variables",
"CSS Will Change",
"CSS Writing Modes",
"CSSOM View",
"Filter Effects",
"Grouping Selectors",
"MathML",
"Media Queries",
"Microsoft Extensions",
"Mozilla Extensions",
"Pointer Events",
"Pseudo",
"Pseudo-classes",
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
]
}
}

View File

@@ -0,0 +1,8 @@
module.exports = {
atRules: require('./at-rules'),
selectors: require('./selectors'),
types: require('./types'),
properties: require('./properties'),
syntaxes: require('./syntaxes'),
units: require('./units'),
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,402 @@
{
"definitions": {
"propertyList": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "string",
"property-reference": {
"comment": "property-reference is an extension to the JSON schema validator. Here it jumps to the root level of the hierarchy and tests if a value is an existing key there (i.e a defined property). See test/validate-schema.js for implementation details.",
"$data": "/"
}
}
},
"animationType": {
"enum": [
"angleBasicShapeOrPath",
"angleOrBasicShapeOrPath",
"basicShapeOtherwiseNo",
"byComputedValueType",
"color",
"discrete",
"eachOfShorthandPropertiesExceptUnicodeBiDiAndDirection",
"filterList",
"fontStretch",
"fontWeight",
"integer",
"length",
"lpc",
"notAnimatable",
"numberOrLength",
"number",
"position",
"rectangle",
"repeatableListOfSimpleListOfLpc",
"shadowList",
"simpleListOfLpc",
"simpleListOfLpcDifferenceLpc",
"transform",
"visibility"
]
},
"percentages": {
"enum": [
"blockSizeOfContainingBlock",
"dependsOnLayoutModel",
"inlineSizeOfContainingBlock",
"lengthsAsPercentages",
"logicalHeightOfContainingBlock",
"logicalWidthOfContainingBlock",
"maxZoomFactor",
"minZoomFactor",
"no",
"referToBorderBox",
"referToContainingBlockHeight",
"referToDimensionOfBorderBox",
"referToDimensionOfContentArea",
"referToElementFontSize",
"referToFlexContainersInnerMainSize",
"referToHeightOfBackgroundPositioningAreaMinusBackgroundImageHeight",
"referToLineBoxWidth",
"referToLineHeight",
"referToParentElementsFontSize",
"referToSizeOfBackgroundPositioningAreaMinusBackgroundImageSize",
"referToSizeOfBorderImage",
"referToSizeOfBoundingBox",
"referToSizeOfContainingBlock",
"referToSizeOfElement",
"referToSizeOfFont",
"referToSizeOfMaskBorderImage",
"referToSizeOfMaskPaintingArea",
"referToTotalPathLength",
"referToWidthAndHeightOfElement",
"referToWidthOfAffectedGlyph",
"referToWidthOfBackgroundPositioningAreaMinusBackgroundImageHeight",
"referToWidthOfContainingBlock",
"referToWidthOrHeightOfBorderImageArea",
"referToReferenceBoxWhenSpecifiedOtherwiseBorderBox",
"regardingHeightOfGeneratedBoxContainingBlockPercentages0",
"regardingHeightOfGeneratedBoxContainingBlockPercentagesNone",
"regardingHeightOfGeneratedBoxContainingBlockPercentagesRelativeToContainingBlock",
"relativeToBackgroundPositioningArea",
"relativeToMaskBorderImageArea",
"relativeToScrollContainerPaddingBoxAxis",
"relativeToTheScrollContainersScrollport",
"relativeToWidthAndHeight"
]
},
"computed": {
"enum": [
"absoluteLength",
"absoluteLength0ForNone",
"absoluteLength0IfColumnRuleStyleNoneOrHidden",
"absoluteLengthOr0IfBorderBottomStyleNoneOrHidden",
"absoluteLengthOr0IfBorderLeftStyleNoneOrHidden",
"absoluteLengthOr0IfBorderRightStyleNoneOrHidden",
"absoluteLengthOr0IfBorderTopStyleNoneOrHidden",
"absoluteLengthOrAsSpecified",
"absoluteLengthOrKeyword",
"absoluteLengthOrNone",
"absoluteLengthOrNormal",
"absoluteLengthOrPercentage",
"absoluteLengthsSpecifiedColorAsSpecified",
"absoluteLengthZeroIfBorderStyleNoneOrHidden",
"absoluteLengthZeroOrLarger",
"absoluteURIOrNone",
"angleRoundedToNextQuarter",
"asAutoOrColor",
"asDefinedForBasicShapeWithAbsoluteURIOtherwiseAsSpecified",
"asLength",
"asSpecified",
"asSpecifiedAppliesToEachProperty",
"asSpecifiedButVisibleOrClipReplacedToAutoOrHiddenIfOtherValueDifferent",
"asSpecifiedExceptMatchParent",
"asSpecifiedExceptPositionedFloatingAndRootElementsKeywordMaybeDifferent",
"asSpecifiedRelativeToAbsoluteLengths",
"asSpecifiedURLsAbsolute",
"asSpecifiedWithExceptionOfResolution",
"asSpecifiedWithLengthsAbsoluteAndNormalComputingToZeroExceptMultiColumn",
"asSpecifiedWithVarsSubstituted",
"autoOnAbsolutelyPositionedElementsValueOfAlignItemsOnParent",
"autoOrRectangle",
"colorPlusThreeAbsoluteLengths",
"computedColor",
"consistsOfTwoDimensionKeywords",
"consistsOfTwoKeywordsForOriginAndOffsets",
"forLengthAbsoluteValueOtherwisePercentage",
"invertForTranslucentColorRGBAOtherwiseRGB",
"keywordOrNumericalValueBolderLighterTransformedToRealValue",
"keywordPlusIntegerIfDigits",
"lengthAbsolutePercentageAsSpecifiedOtherwiseAuto",
"listEachItemConsistingOfAbsoluteLengthPercentageAndOrigin",
"listEachItemHasTwoKeywordsOnePerDimension",
"listEachItemTwoKeywordsOriginOffsets",
"noneOrImageWithAbsoluteURI",
"normalizedAngle",
"normalOnElementsForPseudosNoneAbsoluteURIStringOrAsSpecified",
"oneToFourPercentagesOrAbsoluteLengthsPlusFill",
"optimumMinAndMaxValueOfAbsoluteLengthPercentageOrNormal",
"optimumValueOfAbsoluteLengthOrNormal",
"percentageAsSpecifiedAbsoluteLengthOrNone",
"percentageAsSpecifiedOrAbsoluteLength",
"percentageAutoOrAbsoluteLength",
"percentageOrAbsoluteLengthPlusKeywords",
"sameAsBoxOffsets",
"sameAsMaxWidthAndMaxHeight",
"sameAsMinWidthAndMinHeight",
"sameAsWidthAndHeight",
"specifiedIntegerOrAbsoluteLength",
"specifiedValueClipped0To1",
"specifiedValueNumberClipped0To1",
"translucentValuesRGBAOtherwiseRGB",
"twoAbsoluteLengthOrPercentages",
"twoAbsoluteLengths"
]
},
"appliesto": {
"enum": [
"absolutelyPositionedElements",
"allElements",
"allElementsAcceptingWidthOrHeight",
"allElementsAndPseudos",
"allElementsButNonReplacedAndTableColumns",
"allElementsButNonReplacedAndTableRows",
"allElementsCreatingNativeWindows",
"allElementsExceptGeneratedContentOrPseudoElements",
"allElementsExceptInlineBoxesAndInternalRubyOrTableBoxes",
"allElementsExceptInternalTableDisplayTypes",
"allElementsExceptNonReplacedInlineElementsTableRowsColumnsRowColumnGroups",
"allElementsExceptTableDisplayTypes",
"allElementsExceptTableElementsWhenCollapse",
"allElementsExceptTableRowColumnGroupsTableRowsColumns",
"allElementsExceptTableRowGroupsRowsColumnGroupsAndColumns",
"allElementsNoEffectIfDisplayNone",
"allElementsSomeValuesNoEffectOnNonInlineElements",
"allElementsSVGContainerElements",
"allElementsSVGContainerGraphicsAndGraphicsReferencingElements",
"allElementsThatCanReferenceImages",
"allElementsUAsNotRequiredWhenCollapse",
"anyElementEffectOnProgressAndMeter",
"beforeAndAfterPseudos",
"blockContainerElements",
"blockContainers",
"blockContainersAndMultiColumnContainers",
"blockContainersExceptMultiColumnContainers",
"blockContainersExceptTableWrappers",
"blockContainersFlexContainersGridContainers",
"blockElementsInNormalFlow",
"blockLevelElements",
"blockLevelBoxesAndAbsolutelyPositionedBoxesAndGridItems",
"boxElements",
"childrenOfBoxElements",
"directChildrenOfElementsWithDisplayMozBoxMozInlineBox",
"elementsWithDisplayBoxOrInlineBox",
"elementsWithDisplayMarker",
"elementsWithDisplayMozBoxMozInlineBox",
"elementsWithOverflowNotVisibleAndReplacedElements",
"exclusionElements",
"firstLetterPseudoElementsAndInlineLevelFirstChildren",
"flexContainers",
"flexItemsAndAbsolutelyPositionedFlexContainerChildren",
"flexItemsAndInFlowPseudos",
"flexItemsGridItemsAbsolutelyPositionedContainerChildren",
"flexItemsGridItemsAndAbsolutelyPositionedBoxes",
"floats",
"gridContainers",
"gridContainersWithMasonryLayout",
"gridContainersWithMasonryLayoutInTheirBlockAxis",
"gridContainersWithMasonryLayoutInTheirInlineAxis",
"gridItemsAndBoxesWithinGridContainer",
"iframeElements",
"images",
"inFlowBlockLevelElements",
"inFlowChildrenOfBoxElements",
"inlineLevelAndTableCellElements",
"listItems",
"maskElements",
"multicolElements",
"multiColumnElementsFlexContainersGridContainers",
"multilineFlexContainers",
"nonReplacedBlockAndInlineBlockElements",
"nonReplacedBlockElements",
"nonReplacedElements",
"nonReplacedInlineElements",
"positionedElements",
"replacedElements",
"rubyAnnotationsContainers",
"rubyBasesAnnotationsBaseAnnotationContainers",
"sameAsMargin",
"sameAsWidthAndHeight",
"scrollContainers",
"scrollingBoxes",
"tableCaptionElements",
"tableCellElements",
"tableElements",
"textElements",
"textFields",
"transformableElements",
"xulImageElements"
]
},
"alsoApplyTo": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"enum": [
"::first-letter",
"::first-line",
"::placeholder"
]
}
},
"order": {
"enum": [
"canonicalOrder",
"lengthOrPercentageBeforeKeywordIfBothPresent",
"lengthOrPercentageBeforeKeywords",
"oneOrTwoValuesLengthAbsoluteKeywordsPercentages",
"orderOfAppearance",
"percentagesOrLengthsFollowedByFill",
"perGrammar",
"uniqueOrder"
]
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental",
"obsolete"
]
},
"mdn_url": {
"type": "string",
"pattern": "^https://developer.mozilla.org/docs/"
}
},
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"required": [
"syntax",
"media",
"inherited",
"animationType",
"percentages",
"groups",
"initial",
"appliesto",
"computed",
"order",
"status"
],
"properties": {
"syntax": {
"type": "string"
},
"media": {
"oneOf": [
{
"type": "string",
"enum": [
"all",
"aural",
"continuous",
"interactive",
"none",
"noPracticalMedia",
"paged",
"visual",
"visualInContinuousMediaNoEffectInOverflowColumns"
]
},
{
"type": "array",
"minItems": 2,
"uniqueItems": true,
"items": {
"type": "string",
"enum": [
"interactive",
"paged",
"visual"
]
}
}
]
},
"inherited": {
"type": "boolean"
},
"animationType": {
"oneOf": [
{
"$ref": "#/definitions/animationType"
},
{
"$ref": "#/definitions/propertyList"
}
]
},
"percentages": {
"oneOf": [
{
"$ref": "#/definitions/percentages"
},
{
"$ref": "#/definitions/propertyList"
}
]
},
"groups": {
"type": "array",
"minitems": 1,
"uniqueItems": true,
"items": {
"$ref": "definitions.json#/groupList"
}
},
"initial": {
"oneOf": [
{
"type": "string"
},
{
"$ref": "#/definitions/propertyList"
}
]
},
"appliesto": {
"$ref": "#/definitions/appliesto"
},
"alsoAppliesTo": {
"$ref": "#/definitions/alsoApplyTo"
},
"computed": {
"oneOf": [
{
"$ref": "#/definitions/computed"
},
{
"$ref": "#/definitions/propertyList"
}
]
},
"order": {
"$ref": "#/definitions/order"
},
"stacking": {
"type": "boolean"
},
"status": {
"$ref": "#/definitions/status"
},
"mdn_url": {
"$ref": "#/definitions/mdn_url"
}
}
}
}

View File

@@ -0,0 +1,927 @@
{
"Type selectors": {
"syntax": "element",
"groups": [
"Basic Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Type_selectors"
},
"Class selectors": {
"syntax": ".class",
"groups": [
"Basic Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Class_selectors"
},
"ID selectors": {
"syntax": "#id",
"groups": [
"Basic Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/ID_selectors"
},
"Universal selectors": {
"syntax": "*",
"groups": [
"Basic Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Universal_selectors"
},
"Attribute selectors": {
"syntax": "[attr=value]",
"groups": [
"Basic Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Attribute_selectors"
},
"Selector list": {
"syntax": ",",
"groups": [
"Grouping Selectors",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Selector_list"
},
"Adjacent sibling combinator": {
"syntax": "A + B",
"groups": [
"Combinators",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Adjacent_sibling_combinator"
},
"General sibling combinator": {
"syntax": "A ~ B",
"groups": [
"Combinators",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/General_sibling_combinator"
},
"Child combinator": {
"syntax": "A > B",
"groups": [
"Combinators",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Child_combinator"
},
"Descendant combinator": {
"syntax": "A B",
"groups": [
"Combinators",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Descendant_combinator"
},
"Column combinator": {
"syntax": "A || B",
"groups": [
"Combinators",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Column_combinator"
},
"Pseudo-classes": {
"syntax": ":",
"groups": [
"Pseudo",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Pseudo-classes"
},
"Pseudo-elements": {
"syntax": "::",
"groups": [
"Pseudo",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/Pseudo-elements"
},
":active": {
"syntax": ":active",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:active"
},
":any-link": {
"syntax": ":any-link",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:any-link"
},
":checked": {
"syntax": ":checked",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:checked"
},
":blank": {
"syntax": ":blank",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:blank"
},
":default": {
"syntax": ":default",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:default"
},
":defined": {
"syntax": ":defined",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:defined"
},
":dir": {
"syntax": ":dir( ltr | rtl )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:dir"
},
":disabled": {
"syntax": ":disabled",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:disabled"
},
":empty": {
"syntax": ":empty",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:empty"
},
":enabled": {
"syntax": ":enabled",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:enabled"
},
":first": {
"syntax": ":first",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:first"
},
":first-child": {
"syntax": ":first-child",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:first-child"
},
":first-of-type": {
"syntax": ":first-of-type",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:first-of-type"
},
":fullscreen": {
"syntax": ":fullscreen",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:fullscreen"
},
":focus": {
"syntax": ":focus",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:focus"
},
":focus-visible": {
"syntax": ":focus-visible",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:focus-visible"
},
":focus-within": {
"syntax": ":focus-within",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:focus-within"
},
":has": {
"syntax": ":has( <relative-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:has"
},
":host()": {
"syntax": ":host( <compound-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:host()"
},
":host-context()": {
"syntax": ":host-context( <compound-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:host-context()"
},
":hover": {
"syntax": ":hover",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:hover"
},
":indeterminate": {
"syntax": ":indeterminate",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:indeterminate"
},
":in-range": {
"syntax": ":in-range",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:in-range"
},
":invalid": {
"syntax": ":invalid",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:invalid"
},
":is": {
"syntax": ":is( <complex-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:is"
},
":lang": {
"syntax": ":lang( <language-code> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:lang"
},
":last-child": {
"syntax": ":last-child",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:last-child"
},
":last-of-type": {
"syntax": ":last-of-type",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:last-of-type"
},
":left": {
"syntax": ":left",
"groups": [
"Pseudo-classes",
"Selectors",
"CSS Pages"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:left"
},
":link": {
"syntax": ":link",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:link"
},
":not": {
"syntax": ":not( <complex-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:not"
},
":nth-child": {
"syntax": ":nth-child( <nth> [ of <complex-selector-list> ]? )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:nth-child"
},
":nth-last-child": {
"syntax": ":nth-last-child( <nth> [ of <complex-selector-list> ]? )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:nth-last-child"
},
":nth-last-of-type": {
"syntax": ":nth-last-of-type( <nth> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:nth-last-of-type"
},
":nth-of-type": {
"syntax": ":nth-of-type( <nth> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:nth-of-type"
},
":only-child": {
"syntax": ":only-child",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:only-child"
},
":only-of-type": {
"syntax": ":only-of-type",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:only-of-type"
},
":optional": {
"syntax": ":optional",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:optional"
},
":out-of-range": {
"syntax": ":out-of-range",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:out-of-range"
},
":placeholder-shown": {
"syntax": ":placeholder-shown",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:placeholder-shown"
},
":read-only": {
"syntax": ":read-only",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:read-only"
},
":read-write": {
"syntax": ":read-write",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:read-write"
},
":required": {
"syntax": ":required",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:required"
},
":right": {
"syntax": ":right",
"groups": [
"Pseudo-classes",
"Selectors",
"CSS Pages"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:right"
},
":root": {
"syntax": ":root",
"groups": [
"Pseudo-classes",
"Selectors",
"CSS Pages"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:root"
},
":scope": {
"syntax": ":scope",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:scope"
},
":target": {
"syntax": ":target",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:target"
},
":valid": {
"syntax": ":valid",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:valid"
},
":visited": {
"syntax": ":visited",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:visited"
},
":where": {
"syntax": ":where( <complex-selector-list> )",
"groups": [
"Pseudo-classes",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/:where"
},
"::-moz-progress-bar": {
"syntax": "::-moz-progress-bar",
"groups": [
"Pseudo-elements",
"Selectors",
"Mozilla Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-moz-progress-bar"
},
"::-moz-range-progress": {
"syntax": "::-moz-range-progress",
"groups": [
"Pseudo-elements",
"Selectors",
"Mozilla Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-moz-range-progress"
},
"::-moz-range-thumb": {
"syntax": "::-moz-range-thumb",
"groups": [
"Pseudo-elements",
"Selectors",
"Mozilla Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-moz-range-thumb"
},
"::-moz-range-track": {
"syntax": "::-moz-range-track",
"groups": [
"Pseudo-elements",
"Selectors",
"Mozilla Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-moz-range-track"
},
"::-ms-browse": {
"syntax": "::-ms-browse",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-browse"
},
"::-ms-check": {
"syntax": "::-ms-check",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-check"
},
"::-ms-clear": {
"syntax": "::-ms-clear",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-clear"
},
"::-ms-expand": {
"syntax": "::-ms-clear",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-expand"
},
"::-ms-fill": {
"syntax": "::-ms-fill",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-fill"
},
"::-ms-fill-lower": {
"syntax": "::-ms-fill-lower",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-fill-lower"
},
"::-ms-fill-upper": {
"syntax": "::-ms-fill-upper",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-fill-upper"
},
"::-ms-reveal": {
"syntax": "::-ms-reveal",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-reveal"
},
"::-ms-thumb": {
"syntax": "::-ms-thumb",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-thumb"
},
"::-ms-ticks-after": {
"syntax": "::-ms-ticks-after",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-ticks-after"
},
"::-ms-ticks-before": {
"syntax": "::-ms-ticks-before",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-ticks-before"
},
"::-ms-tooltip": {
"syntax": "::-ms-tooltip",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-tooltip"
},
"::-ms-track": {
"syntax": "::-ms-track",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-track"
},
"::-ms-value": {
"syntax": "::-ms-value",
"groups": [
"Pseudo-elements",
"Selectors",
"Microsoft Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-ms-value"
},
"::-webkit-progress-bar": {
"syntax": "::-webkit-progress-bar",
"groups": [
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-webkit-progress-bar"
},
"::-webkit-progress-inner-value": {
"syntax": "::-webkit-progress-inner-value",
"groups": [
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
],
"status": "nonstandard"
},
"::-webkit-progress-value": {
"syntax": "::-webkit-progress-value",
"groups": [
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-webkit-progress-value"
},
"::-webkit-slider-runnable-track": {
"syntax": "::-webkit-slider-runnable-track",
"groups": [
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-webkit-slider-runnable-track"
},
"::-webkit-slider-thumb": {
"syntax": "::-webkit-slider-thumb",
"groups": [
"Pseudo-elements",
"Selectors",
"WebKit Extensions"
],
"status": "nonstandard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::-webkit-slider-thumb"
},
"::after": {
"syntax": "/* CSS3 syntax */\n::after\n\n/* CSS2 syntax */\n:after",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::after"
},
"::backdrop": {
"syntax": "::backdrop",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::backdrop"
},
"::before": {
"syntax": "/* CSS3 syntax */\n::before\n\n/* CSS2 syntax */\n:before",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::before"
},
"::cue": {
"syntax": "::cue | ::cue( <selector> )",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::cue"
},
"::cue-region": {
"syntax": "::cue-region | ::cue-region( <selector> )",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::cue-region"
},
"::first-letter": {
"syntax": "/* CSS3 syntax */\n::first-letter\n\n/* CSS2 syntax */\n:first-letter",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::first-letter"
},
"::first-line": {
"syntax": "/* CSS3 syntax */\n::first-line\n\n/* CSS2 syntax */\n:first-line",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::first-line"
},
"::grammar-error": {
"syntax": "::grammar-error",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::grammar-error"
},
"::marker": {
"syntax": "::marker",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::marker"
},
"::part": {
"syntax": "::part( <ident>+ )",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::part"
},
"::placeholder": {
"syntax": "::placeholder",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::placeholder"
},
"::selection": {
"syntax": "::selection",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::selection"
},
"::slotted": {
"syntax": "::slotted( <compound-selector-list> )",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::slotted"
},
"::spelling-error": {
"syntax": "::spelling-error",
"groups": [
"Pseudo-elements",
"Selectors"
],
"status": "experimental",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/::spelling-error"
}
}

View File

@@ -0,0 +1,36 @@
{
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"syntax": {
"type": "string"
},
"groups": {
"type": "array",
"minitems": 1,
"uniqueItems": true,
"items": {
"$ref": "definitions.json#/groupList"
}
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental"
]
},
"mdn_url": {
"type": "string",
"pattern": "^https://developer.mozilla.org/docs/Web/CSS/"
}
},
"required": [
"syntax",
"groups",
"status"
]
}
}

View File

@@ -0,0 +1,761 @@
{
"absolute-size": {
"syntax": "xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large"
},
"alpha-value": {
"syntax": "<number> | <percentage>"
},
"angle-percentage": {
"syntax": "<angle> | <percentage>"
},
"angular-color-hint": {
"syntax": "<angle-percentage>"
},
"angular-color-stop": {
"syntax": "<color> && <color-stop-angle>?"
},
"angular-color-stop-list": {
"syntax": "[ <angular-color-stop> [, <angular-color-hint>]? ]# , <angular-color-stop>"
},
"animateable-feature": {
"syntax": "scroll-position | contents | <custom-ident>"
},
"attachment": {
"syntax": "scroll | fixed | local"
},
"attr()": {
"syntax": "attr( <attr-name> <type-or-unit>? [, <attr-fallback> ]? )"
},
"attr-matcher": {
"syntax": "[ '~' | '|' | '^' | '$' | '*' ]? '='"
},
"attr-modifier": {
"syntax": "i | s"
},
"attribute-selector": {
"syntax": "'[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'"
},
"auto-repeat": {
"syntax": "repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )"
},
"auto-track-list": {
"syntax": "[ <line-names>? [ <fixed-size> | <fixed-repeat> ] ]* <line-names>? <auto-repeat>\n[ <line-names>? [ <fixed-size> | <fixed-repeat> ] ]* <line-names>?"
},
"baseline-position": {
"syntax": "[ first | last ]? baseline"
},
"basic-shape": {
"syntax": "<inset()> | <circle()> | <ellipse()> | <polygon()> | <path()>"
},
"bg-image": {
"syntax": "none | <image>"
},
"bg-layer": {
"syntax": "<bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box> || <box>"
},
"bg-position": {
"syntax": "[ [ left | center | right | top | bottom | <length-percentage> ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ] | [ center | [ left | right ] <length-percentage>? ] && [ center | [ top | bottom ] <length-percentage>? ] ]"
},
"bg-size": {
"syntax": "[ <length-percentage> | auto ]{1,2} | cover | contain"
},
"blur()": {
"syntax": "blur( <length> )"
},
"blend-mode": {
"syntax": "normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity"
},
"box": {
"syntax": "border-box | padding-box | content-box"
},
"brightness()": {
"syntax": "brightness( <number-percentage> )"
},
"calc()": {
"syntax": "calc( <calc-sum> )"
},
"calc-sum": {
"syntax": "<calc-product> [ [ '+' | '-' ] <calc-product> ]*"
},
"calc-product": {
"syntax": "<calc-value> [ '*' <calc-value> | '/' <number> ]*"
},
"calc-value": {
"syntax": "<number> | <dimension> | <percentage> | ( <calc-sum> )"
},
"cf-final-image": {
"syntax": "<image> | <color>"
},
"cf-mixing-image": {
"syntax": "<percentage>? && <image>"
},
"circle()": {
"syntax": "circle( [ <shape-radius> ]? [ at <position> ]? )"
},
"clamp()": {
"syntax": "clamp( <calc-sum>#{3} )"
},
"class-selector": {
"syntax": "'.' <ident-token>"
},
"clip-source": {
"syntax": "<url>"
},
"color": {
"syntax": "<rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>"
},
"color-stop": {
"syntax": "<color-stop-length> | <color-stop-angle>"
},
"color-stop-angle": {
"syntax": "<angle-percentage>{1,2}"
},
"color-stop-length": {
"syntax": "<length-percentage>{1,2}"
},
"color-stop-list": {
"syntax": "[ <linear-color-stop> [, <linear-color-hint>]? ]# , <linear-color-stop>"
},
"combinator": {
"syntax": "'>' | '+' | '~' | [ '||' ]"
},
"common-lig-values": {
"syntax": "[ common-ligatures | no-common-ligatures ]"
},
"compat-auto": {
"syntax": "searchfield | textarea | push-button | slider-horizontal | checkbox | radio | square-button | menulist | listbox | meter | progress-bar | button"
},
"composite-style": {
"syntax": "clear | copy | source-over | source-in | source-out | source-atop | destination-over | destination-in | destination-out | destination-atop | xor"
},
"compositing-operator": {
"syntax": "add | subtract | intersect | exclude"
},
"compound-selector": {
"syntax": "[ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!"
},
"compound-selector-list": {
"syntax": "<compound-selector>#"
},
"complex-selector": {
"syntax": "<compound-selector> [ <combinator>? <compound-selector> ]*"
},
"complex-selector-list": {
"syntax": "<complex-selector>#"
},
"conic-gradient()": {
"syntax": "conic-gradient( [ from <angle> ]? [ at <position> ]?, <angular-color-stop-list> )"
},
"contextual-alt-values": {
"syntax": "[ contextual | no-contextual ]"
},
"content-distribution": {
"syntax": "space-between | space-around | space-evenly | stretch"
},
"content-list": {
"syntax": "[ <string> | contents | <image> | <quote> | <target> | <leader()> ]+"
},
"content-position": {
"syntax": "center | start | end | flex-start | flex-end"
},
"content-replacement": {
"syntax": "<image>"
},
"contrast()": {
"syntax": "contrast( [ <number-percentage> ] )"
},
"counter()": {
"syntax": "counter( <custom-ident>, <counter-style>? )"
},
"counter-style": {
"syntax": "<counter-style-name> | symbols()"
},
"counter-style-name": {
"syntax": "<custom-ident>"
},
"counters()": {
"syntax": "counters( <custom-ident>, <string>, <counter-style>? )"
},
"cross-fade()": {
"syntax": "cross-fade( <cf-mixing-image> , <cf-final-image>? )"
},
"cubic-bezier-timing-function": {
"syntax": "ease | ease-in | ease-out | ease-in-out | cubic-bezier(<number [0,1]>, <number>, <number [0,1]>, <number>)"
},
"deprecated-system-color": {
"syntax": "ActiveBorder | ActiveCaption | AppWorkspace | Background | ButtonFace | ButtonHighlight | ButtonShadow | ButtonText | CaptionText | GrayText | Highlight | HighlightText | InactiveBorder | InactiveCaption | InactiveCaptionText | InfoBackground | InfoText | Menu | MenuText | Scrollbar | ThreeDDarkShadow | ThreeDFace | ThreeDHighlight | ThreeDLightShadow | ThreeDShadow | Window | WindowFrame | WindowText"
},
"discretionary-lig-values": {
"syntax": "[ discretionary-ligatures | no-discretionary-ligatures ]"
},
"display-box": {
"syntax": "contents | none"
},
"display-inside": {
"syntax": "flow | flow-root | table | flex | grid | ruby"
},
"display-internal": {
"syntax": "table-row-group | table-header-group | table-footer-group | table-row | table-cell | table-column-group | table-column | table-caption | ruby-base | ruby-text | ruby-base-container | ruby-text-container"
},
"display-legacy": {
"syntax": "inline-block | inline-list-item | inline-table | inline-flex | inline-grid"
},
"display-listitem": {
"syntax": "<display-outside>? && [ flow | flow-root ]? && list-item"
},
"display-outside": {
"syntax": "block | inline | run-in"
},
"drop-shadow()": {
"syntax": "drop-shadow( <length>{2,3} <color>? )"
},
"east-asian-variant-values": {
"syntax": "[ jis78 | jis83 | jis90 | jis04 | simplified | traditional ]"
},
"east-asian-width-values": {
"syntax": "[ full-width | proportional-width ]"
},
"element()": {
"syntax": "element( <id-selector> )"
},
"ellipse()": {
"syntax": "ellipse( [ <shape-radius>{2} ]? [ at <position> ]? )"
},
"ending-shape": {
"syntax": "circle | ellipse"
},
"env()": {
"syntax": "env( <custom-ident> , <declaration-value>? )"
},
"explicit-track-list": {
"syntax": "[ <line-names>? <track-size> ]+ <line-names>?"
},
"family-name": {
"syntax": "<string> | <custom-ident>+"
},
"feature-tag-value": {
"syntax": "<string> [ <integer> | on | off ]?"
},
"feature-type": {
"syntax": "@stylistic | @historical-forms | @styleset | @character-variant | @swash | @ornaments | @annotation"
},
"feature-value-block": {
"syntax": "<feature-type> '{' <feature-value-declaration-list> '}'"
},
"feature-value-block-list": {
"syntax": "<feature-value-block>+"
},
"feature-value-declaration": {
"syntax": "<custom-ident>: <integer>+;"
},
"feature-value-declaration-list": {
"syntax": "<feature-value-declaration>"
},
"feature-value-name": {
"syntax": "<custom-ident>"
},
"fill-rule": {
"syntax": "nonzero | evenodd"
},
"filter-function": {
"syntax": "<blur()> | <brightness()> | <contrast()> | <drop-shadow()> | <grayscale()> | <hue-rotate()> | <invert()> | <opacity()> | <saturate()> | <sepia()>"
},
"filter-function-list": {
"syntax": "[ <filter-function> | <url> ]+"
},
"final-bg-layer": {
"syntax": "<'background-color'> || <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box> || <box>"
},
"fit-content()": {
"syntax": "fit-content( [ <length> | <percentage> ] )"
},
"fixed-breadth": {
"syntax": "<length-percentage>"
},
"fixed-repeat": {
"syntax": "repeat( [ <positive-integer> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )"
},
"fixed-size": {
"syntax": "<fixed-breadth> | minmax( <fixed-breadth> , <track-breadth> ) | minmax( <inflexible-breadth> , <fixed-breadth> )"
},
"font-stretch-absolute": {
"syntax": "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | <percentage>"
},
"font-variant-css21": {
"syntax": "[ normal | small-caps ]"
},
"font-weight-absolute": {
"syntax": "normal | bold | <number [1,1000]>"
},
"frequency-percentage": {
"syntax": "<frequency> | <percentage>"
},
"general-enclosed": {
"syntax": "[ <function-token> <any-value> ) ] | ( <ident> <any-value> )"
},
"generic-family": {
"syntax": "serif | sans-serif | cursive | fantasy | monospace"
},
"generic-name": {
"syntax": "serif | sans-serif | cursive | fantasy | monospace"
},
"geometry-box": {
"syntax": "<shape-box> | fill-box | stroke-box | view-box"
},
"gradient": {
"syntax": "<linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>"
},
"grayscale()": {
"syntax": "grayscale( <number-percentage> )"
},
"grid-line": {
"syntax": "auto | <custom-ident> | [ <integer> && <custom-ident>? ] | [ span && [ <integer> || <custom-ident> ] ]"
},
"historical-lig-values": {
"syntax": "[ historical-ligatures | no-historical-ligatures ]"
},
"hsl()": {
"syntax": "hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )"
},
"hsla()": {
"syntax": "hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )"
},
"hue": {
"syntax": "<number> | <angle>"
},
"hue-rotate()": {
"syntax": "hue-rotate( <angle> )"
},
"id-selector": {
"syntax": "<hash-token>"
},
"image": {
"syntax": "<url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>"
},
"image()": {
"syntax": "image( <image-tags>? [ <image-src>? , <color>? ]! )"
},
"image-set()": {
"syntax": "image-set( <image-set-option># )"
},
"image-set-option": {
"syntax": "[ <image> | <string> ] <resolution>"
},
"image-src": {
"syntax": "<url> | <string>"
},
"image-tags": {
"syntax": "ltr | rtl"
},
"inflexible-breadth": {
"syntax": "<length> | <percentage> | min-content | max-content | auto"
},
"inset()": {
"syntax": "inset( <length-percentage>{1,4} [ round <'border-radius'> ]? )"
},
"invert()": {
"syntax": "invert( <number-percentage> )"
},
"keyframes-name": {
"syntax": "<custom-ident> | <string>"
},
"keyframe-block": {
"syntax": "<keyframe-selector># {\n <declaration-list>\n}"
},
"keyframe-block-list": {
"syntax": "<keyframe-block>+"
},
"keyframe-selector": {
"syntax": "from | to | <percentage>"
},
"leader()": {
"syntax": "leader( <leader-type> )"
},
"leader-type": {
"syntax": "dotted | solid | space | <string>"
},
"length-percentage": {
"syntax": "<length> | <percentage>"
},
"line-names": {
"syntax": "'[' <custom-ident>* ']'"
},
"line-name-list": {
"syntax": "[ <line-names> | <name-repeat> ]+"
},
"line-style": {
"syntax": "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset"
},
"line-width": {
"syntax": "<length> | thin | medium | thick"
},
"linear-color-hint": {
"syntax": "<length-percentage>"
},
"linear-color-stop": {
"syntax": "<color> <color-stop-length>?"
},
"linear-gradient()": {
"syntax": "linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )"
},
"mask-layer": {
"syntax": "<mask-reference> || <position> [ / <bg-size> ]? || <repeat-style> || <geometry-box> || [ <geometry-box> | no-clip ] || <compositing-operator> || <masking-mode>"
},
"mask-position": {
"syntax": "[ <length-percentage> | left | center | right ] [ <length-percentage> | top | center | bottom ]?"
},
"mask-reference": {
"syntax": "none | <image> | <mask-source>"
},
"mask-source": {
"syntax": "<url>"
},
"masking-mode": {
"syntax": "alpha | luminance | match-source"
},
"matrix()": {
"syntax": "matrix( <number>#{6} )"
},
"matrix3d()": {
"syntax": "matrix3d( <number>#{16} )"
},
"max()": {
"syntax": "max( <calc-sum># )"
},
"media-and": {
"syntax": "<media-in-parens> [ and <media-in-parens> ]+"
},
"media-condition": {
"syntax": "<media-not> | <media-and> | <media-or> | <media-in-parens>"
},
"media-condition-without-or": {
"syntax": "<media-not> | <media-and> | <media-in-parens>"
},
"media-feature": {
"syntax": "( [ <mf-plain> | <mf-boolean> | <mf-range> ] )"
},
"media-in-parens": {
"syntax": "( <media-condition> ) | <media-feature> | <general-enclosed>"
},
"media-not": {
"syntax": "not <media-in-parens>"
},
"media-or": {
"syntax": "<media-in-parens> [ or <media-in-parens> ]+"
},
"media-query": {
"syntax": "<media-condition> | [ not | only ]? <media-type> [ and <media-condition-without-or> ]?"
},
"media-query-list": {
"syntax": "<media-query>#"
},
"media-type": {
"syntax": "<ident>"
},
"mf-boolean": {
"syntax": "<mf-name>"
},
"mf-name": {
"syntax": "<ident>"
},
"mf-plain": {
"syntax": "<mf-name> : <mf-value>"
},
"mf-range": {
"syntax": "<mf-name> [ '<' | '>' ]? '='? <mf-value>\n| <mf-value> [ '<' | '>' ]? '='? <mf-name>\n| <mf-value> '<' '='? <mf-name> '<' '='? <mf-value>\n| <mf-value> '>' '='? <mf-name> '>' '='? <mf-value>"
},
"mf-value": {
"syntax": "<number> | <dimension> | <ident> | <ratio>"
},
"min()": {
"syntax": "min( <calc-sum># )"
},
"minmax()": {
"syntax": "minmax( [ <length> | <percentage> | min-content | max-content | auto ] , [ <length> | <percentage> | <flex> | min-content | max-content | auto ] )"
},
"named-color": {
"syntax": "transparent | aliceblue | antiquewhite | aqua | aquamarine | azure | beige | bisque | black | blanchedalmond | blue | blueviolet | brown | burlywood | cadetblue | chartreuse | chocolate | coral | cornflowerblue | cornsilk | crimson | cyan | darkblue | darkcyan | darkgoldenrod | darkgray | darkgreen | darkgrey | darkkhaki | darkmagenta | darkolivegreen | darkorange | darkorchid | darkred | darksalmon | darkseagreen | darkslateblue | darkslategray | darkslategrey | darkturquoise | darkviolet | deeppink | deepskyblue | dimgray | dimgrey | dodgerblue | firebrick | floralwhite | forestgreen | fuchsia | gainsboro | ghostwhite | gold | goldenrod | gray | green | greenyellow | grey | honeydew | hotpink | indianred | indigo | ivory | khaki | lavender | lavenderblush | lawngreen | lemonchiffon | lightblue | lightcoral | lightcyan | lightgoldenrodyellow | lightgray | lightgreen | lightgrey | lightpink | lightsalmon | lightseagreen | lightskyblue | lightslategray | lightslategrey | lightsteelblue | lightyellow | lime | limegreen | linen | magenta | maroon | mediumaquamarine | mediumblue | mediumorchid | mediumpurple | mediumseagreen | mediumslateblue | mediumspringgreen | mediumturquoise | mediumvioletred | midnightblue | mintcream | mistyrose | moccasin | navajowhite | navy | oldlace | olive | olivedrab | orange | orangered | orchid | palegoldenrod | palegreen | paleturquoise | palevioletred | papayawhip | peachpuff | peru | pink | plum | powderblue | purple | rebeccapurple | red | rosybrown | royalblue | saddlebrown | salmon | sandybrown | seagreen | seashell | sienna | silver | skyblue | slateblue | slategray | slategrey | snow | springgreen | steelblue | tan | teal | thistle | tomato | turquoise | violet | wheat | white | whitesmoke | yellow | yellowgreen"
},
"namespace-prefix": {
"syntax": "<ident>"
},
"ns-prefix": {
"syntax": "[ <ident-token> | '*' ]? '|'"
},
"number-percentage": {
"syntax": "<number> | <percentage>"
},
"numeric-figure-values": {
"syntax": "[ lining-nums | oldstyle-nums ]"
},
"numeric-fraction-values": {
"syntax": "[ diagonal-fractions | stacked-fractions ]"
},
"numeric-spacing-values": {
"syntax": "[ proportional-nums | tabular-nums ]"
},
"nth": {
"syntax": "<an-plus-b> | even | odd"
},
"opacity()": {
"syntax": "opacity( [ <number-percentage> ] )"
},
"overflow-position": {
"syntax": "unsafe | safe"
},
"outline-radius": {
"syntax": "<length> | <percentage>"
},
"page-body": {
"syntax": "<declaration>? [ ; <page-body> ]? | <page-margin-box> <page-body>"
},
"page-margin-box": {
"syntax": "<page-margin-box-type> '{' <declaration-list> '}'"
},
"page-margin-box-type": {
"syntax": "@top-left-corner | @top-left | @top-center | @top-right | @top-right-corner | @bottom-left-corner | @bottom-left | @bottom-center | @bottom-right | @bottom-right-corner | @left-top | @left-middle | @left-bottom | @right-top | @right-middle | @right-bottom"
},
"page-selector-list": {
"syntax": "[ <page-selector># ]?"
},
"page-selector": {
"syntax": "<pseudo-page>+ | <ident> <pseudo-page>*"
},
"path()": {
"syntax": "path( [ <fill-rule>, ]? <string> )"
},
"paint()": {
"syntax": "paint( <ident>, <declaration-value>? )"
},
"perspective()": {
"syntax": "perspective( <length> )"
},
"polygon()": {
"syntax": "polygon( <fill-rule>? , [ <length-percentage> <length-percentage> ]# )"
},
"position": {
"syntax": "[ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]"
},
"pseudo-class-selector": {
"syntax": "':' <ident-token> | ':' <function-token> <any-value> ')'"
},
"pseudo-element-selector": {
"syntax": "':' <pseudo-class-selector>"
},
"pseudo-page": {
"syntax": ": [ left | right | first | blank ]"
},
"quote": {
"syntax": "open-quote | close-quote | no-open-quote | no-close-quote"
},
"radial-gradient()": {
"syntax": "radial-gradient( [ <ending-shape> || <size> ]? [ at <position> ]? , <color-stop-list> )"
},
"relative-selector": {
"syntax": "<combinator>? <complex-selector>"
},
"relative-selector-list": {
"syntax": "<relative-selector>#"
},
"relative-size": {
"syntax": "larger | smaller"
},
"repeat-style": {
"syntax": "repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}"
},
"repeating-linear-gradient()": {
"syntax": "repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )"
},
"repeating-radial-gradient()": {
"syntax": "repeating-radial-gradient( [ <ending-shape> || <size> ]? [ at <position> ]? , <color-stop-list> )"
},
"rgb()": {
"syntax": "rgb( <percentage>{3} [ / <alpha-value> ]? ) | rgb( <number>{3} [ / <alpha-value> ]? ) | rgb( <percentage>#{3} , <alpha-value>? ) | rgb( <number>#{3} , <alpha-value>? )"
},
"rgba()": {
"syntax": "rgba( <percentage>{3} [ / <alpha-value> ]? ) | rgba( <number>{3} [ / <alpha-value> ]? ) | rgba( <percentage>#{3} , <alpha-value>? ) | rgba( <number>#{3} , <alpha-value>? )"
},
"rotate()": {
"syntax": "rotate( [ <angle> | <zero> ] )"
},
"rotate3d()": {
"syntax": "rotate3d( <number> , <number> , <number> , [ <angle> | <zero> ] )"
},
"rotateX()": {
"syntax": "rotateX( [ <angle> | <zero> ] )"
},
"rotateY()": {
"syntax": "rotateY( [ <angle> | <zero> ] )"
},
"rotateZ()": {
"syntax": "rotateZ( [ <angle> | <zero> ] )"
},
"saturate()": {
"syntax": "saturate( <number-percentage> )"
},
"scale()": {
"syntax": "scale( <number> , <number>? )"
},
"scale3d()": {
"syntax": "scale3d( <number> , <number> , <number> )"
},
"scaleX()": {
"syntax": "scaleX( <number> )"
},
"scaleY()": {
"syntax": "scaleY( <number> )"
},
"scaleZ()": {
"syntax": "scaleZ( <number> )"
},
"self-position": {
"syntax": "center | start | end | self-start | self-end | flex-start | flex-end"
},
"shape-radius": {
"syntax": "<length-percentage> | closest-side | farthest-side"
},
"skew()": {
"syntax": "skew( [ <angle> | <zero> ] , [ <angle> | <zero> ]? )"
},
"skewX()": {
"syntax": "skewX( [ <angle> | <zero> ] )"
},
"skewY()": {
"syntax": "skewY( [ <angle> | <zero> ] )"
},
"sepia()": {
"syntax": "sepia( <number-percentage> )"
},
"shadow": {
"syntax": "inset? && <length>{2,4} && <color>?"
},
"shadow-t": {
"syntax": "[ <length>{2,3} && <color>? ]"
},
"shape": {
"syntax": "rect(<top>, <right>, <bottom>, <left>)"
},
"shape-box": {
"syntax": "<box> | margin-box"
},
"side-or-corner": {
"syntax": "[ left | right ] || [ top | bottom ]"
},
"single-animation": {
"syntax": "<time> || <timing-function> || <time> || <single-animation-iteration-count> || <single-animation-direction> || <single-animation-fill-mode> || <single-animation-play-state> || [ none | <keyframes-name> ]"
},
"single-animation-direction": {
"syntax": "normal | reverse | alternate | alternate-reverse"
},
"single-animation-fill-mode": {
"syntax": "none | forwards | backwards | both"
},
"single-animation-iteration-count": {
"syntax": "infinite | <number>"
},
"single-animation-play-state": {
"syntax": "running | paused"
},
"single-transition": {
"syntax": "[ none | <single-transition-property> ] || <time> || <timing-function> || <time>"
},
"single-transition-property": {
"syntax": "all | <custom-ident>"
},
"size": {
"syntax": "closest-side | farthest-side | closest-corner | farthest-corner | <length> | <length-percentage>{2}"
},
"step-position": {
"syntax": "jump-start | jump-end | jump-none | jump-both | start | end"
},
"step-timing-function": {
"syntax": "step-start | step-end | steps(<integer>[, <step-position>]?)"
},
"subclass-selector": {
"syntax": "<id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector>"
},
"supports-condition": {
"syntax": "not <supports-in-parens> | <supports-in-parens> [ and <supports-in-parens> ]* | <supports-in-parens> [ or <supports-in-parens> ]*"
},
"supports-in-parens": {
"syntax": "( <supports-condition> ) | <supports-feature> | <general-enclosed>"
},
"supports-feature": {
"syntax": "<supports-decl> | <supports-selector-fn>"
},
"supports-decl": {
"syntax": "( <declaration> )"
},
"supports-selector-fn": {
"syntax": "selector( <complex-selector> )"
},
"symbol": {
"syntax": "<string> | <image> | <custom-ident>"
},
"target": {
"syntax": "<target-counter()> | <target-counters()> | <target-text()>"
},
"target-counter()": {
"syntax": "target-counter( [ <string> | <url> ] , <custom-ident> , <counter-style>? )"
},
"target-counters()": {
"syntax": "target-counters( [ <string> | <url> ] , <custom-ident> , <string> , <counter-style>? )"
},
"target-text()": {
"syntax": "target-text( [ <string> | <url> ] , [ content | before | after | first-letter ]? )"
},
"time-percentage": {
"syntax": "<time> | <percentage>"
},
"timing-function": {
"syntax": "linear | <cubic-bezier-timing-function> | <step-timing-function>"
},
"track-breadth": {
"syntax": "<length-percentage> | <flex> | min-content | max-content | auto"
},
"track-list": {
"syntax": "[ <line-names>? [ <track-size> | <track-repeat> ] ]+ <line-names>?"
},
"track-repeat": {
"syntax": "repeat( [ <positive-integer> ] , [ <line-names>? <track-size> ]+ <line-names>? )"
},
"track-size": {
"syntax": "<track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( [ <length> | <percentage> ] )"
},
"transform-function": {
"syntax": "<matrix()> | <translate()> | <translateX()> | <translateY()> | <scale()> | <scaleX()> | <scaleY()> | <rotate()> | <skew()> | <skewX()> | <skewY()> | <matrix3d()> | <translate3d()> | <translateZ()> | <scale3d()> | <scaleZ()> | <rotate3d()> | <rotateX()> | <rotateY()> | <rotateZ()> | <perspective()>"
},
"transform-list": {
"syntax": "<transform-function>+"
},
"translate()": {
"syntax": "translate( <length-percentage> , <length-percentage>? )"
},
"translate3d()": {
"syntax": "translate3d( <length-percentage> , <length-percentage> , <length> )"
},
"translateX()": {
"syntax": "translateX( <length-percentage> )"
},
"translateY()": {
"syntax": "translateY( <length-percentage> )"
},
"translateZ()": {
"syntax": "translateZ( <length> )"
},
"type-or-unit": {
"syntax": "string | color | url | integer | number | length | angle | time | frequency | cap | ch | em | ex | ic | lh | rlh | rem | vb | vi | vw | vh | vmin | vmax | mm | Q | cm | in | pt | pc | px | deg | grad | rad | turn | ms | s | Hz | kHz | %"
},
"type-selector": {
"syntax": "<wq-name> | <ns-prefix>? '*'"
},
"var()": {
"syntax": "var( <custom-property-name> , <declaration-value>? )"
},
"viewport-length": {
"syntax": "auto | <length-percentage>"
},
"wq-name": {
"syntax": "<ns-prefix>? <ident-token>"
}
}

View File

@@ -0,0 +1,15 @@
{
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"required": [
"syntax"
],
"properties": {
"syntax": {
"type": "string"
}
}
}
}

View File

@@ -0,0 +1,265 @@
{
"an-plus-b": {
"groups": [
"Selectors"
],
"status": "standard"
},
"angle": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/angle"
},
"angle-percentage": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/angle-percentage"
},
"basic-shape": {
"groups": [
"CSS Shapes",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/basic-shape"
},
"blend-mode": {
"groups": [
"Compositing and Blending",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/blend-mode"
},
"color": {
"groups": [
"CSS Color",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/color_value"
},
"custom-ident": {
"groups": [
"CSS Will Change",
"CSS Counter Styles",
"CSS Lists and Counters",
"CSS Animations",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/custom-ident"
},
"dimension": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/dimension"
},
"display-outside": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-outside"
},
"display-inside": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-inside"
},
"display-listitem": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-listitem"
},
"display-internal": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-internal"
},
"display-box": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-box"
},
"display-legacy": {
"groups": [
"CSS Display"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/display-legacy"
},
"filter-function": {
"groups": [
"Filter Effects"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/filter-function"
},
"flex": {
"groups": [
"CSS Grid Layout",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/flex_value"
},
"frequency": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/frequency"
},
"frequency-percentage": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/frequency-percentage"
},
"gradient": {
"groups": [
"CSS Images",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/gradient"
},
"ident": {
"groups": [
"CSS Types"
],
"status": "standard"
},
"image": {
"groups": [
"CSS Images",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/image"
},
"integer": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/integer"
},
"length": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/length"
},
"length-percentage": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/length-percentage"
},
"number": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/number"
},
"percentage": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/percentage"
},
"position": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/position_value"
},
"ratio": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/ratio"
},
"resolution": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/resolution"
},
"shape": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/shape"
},
"string": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/string"
},
"time": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/time"
},
"time-percentage": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/time-percentage"
},
"timing-function": {
"groups": [
"CSS Animations",
"CSS Transitions",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/timing-function"
},
"transform-function": {
"groups": [
"CSS Transforms",
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/transform-function"
},
"url": {
"groups": [
"CSS Types"
],
"status": "standard",
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/url"
}
}

View File

@@ -0,0 +1,32 @@
{
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"groups": {
"type": "array",
"minitems": 1,
"uniqueItems": true,
"items": {
"$ref": "definitions.json#/groupList"
}
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental"
]
},
"mdn_url": {
"type": "string",
"pattern": "^https://developer.mozilla.org/docs/Web/CSS/"
}
},
"required": [
"groups",
"status"
]
}
}

View File

@@ -0,0 +1,199 @@
{
"ch": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"cm": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"deg": {
"groups": [
"CSS Units",
"CSS Angles"
],
"status": "standard"
},
"dpcm": {
"groups": [
"CSS Units",
"CSS Resolutions"
],
"status": "standard"
},
"dpi": {
"groups": [
"CSS Units",
"CSS Resolutions"
],
"status": "standard"
},
"dppx": {
"groups": [
"CSS Units",
"CSS Resolutions"
],
"status": "standard"
},
"em": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"ex": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"fr": {
"groups": [
"CSS Units",
"CSS Flexible Lengths",
"CSS Grid Layout"
],
"status": "standard"
},
"grad": {
"groups": [
"CSS Units",
"CSS Angles"
],
"status": "standard"
},
"Hz": {
"groups": [
"CSS Units",
"CSS Frequencies"
],
"status": "standard"
},
"in": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"kHz": {
"groups": [
"CSS Units",
"CSS Frequencies"
],
"status": "standard"
},
"mm": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"ms": {
"groups": [
"CSS Units",
"CSS Times"
],
"status": "standard"
},
"pc": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"pt": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"px": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"Q": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"rad": {
"groups": [
"CSS Units",
"CSS Angles"
],
"status": "standard"
},
"rem": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"s": {
"groups": [
"CSS Units",
"CSS Times"
],
"status": "standard"
},
"turn": {
"groups": [
"CSS Units",
"CSS Angles"
],
"status": "standard"
},
"vh": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"vmax": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"vmin": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"vw": {
"groups": [
"CSS Units",
"CSS Lengths"
],
"status": "standard"
},
"x": {
"groups": [
"CSS Units",
"CSS Resolutions"
],
"status": "standard"
}
}

View File

@@ -0,0 +1,28 @@
{
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"groups": {
"type": "array",
"minitems": 1,
"uniqueItems": true,
"items": {
"$ref": "definitions.json#/groupList"
}
},
"status": {
"enum": [
"standard",
"nonstandard",
"experimental"
]
}
},
"required": [
"groups",
"status"
]
}
}

View File

@@ -0,0 +1,5 @@
module.exports = {
api: require('./api'),
css: require('./css'),
l10n: require('./l10n'),
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
module.exports = {
css: require('./css'),
}

View File

@@ -0,0 +1,39 @@
{
"name": "mdn-data",
"version": "2.0.14",
"description": "Open Web data by the Mozilla Developer Network",
"main": "index.js",
"files": [
"api/index.js",
"api/*.json",
"css/index.js",
"css/*.json",
"l10n/index.js",
"l10n/*.json"
],
"repository": {
"type": "git",
"url": "https://github.com/mdn/data.git"
},
"keywords": [
"data",
"mdn",
"mozilla",
"css"
],
"author": "Mozilla Developer Network",
"license": "CC0-1.0",
"bugs": {
"url": "https://github.com/mdn/data/issues"
},
"homepage": "https://developer.mozilla.org",
"devDependencies": {
"ajv": "^5.0.1",
"better-ajv-errors": "^0.5.1"
},
"scripts": {
"lint": "node test/lint",
"travis": "npm test",
"test": "npm run lint"
}
}

View File

@@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View File

@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,742 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

View File

@@ -0,0 +1,73 @@
{
"name": "source-map",
"description": "Generates and consumes source maps",
"version": "0.6.1",
"homepage": "https://github.com/mozilla/source-map",
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
"contributors": [
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/mozilla/source-map.git"
},
"main": "./source-map.js",
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"engines": {
"node": ">=0.10.0"
},
"license": "BSD-3-Clause",
"scripts": {
"test": "npm run build && node test/run-tests.js",
"build": "webpack --color",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"typings": "source-map"
}

View File

@@ -0,0 +1,98 @@
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
export interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
}
export interface Position {
line: number;
column: number;
}
export interface LineRange extends Position {
lastColumn: number;
}
export interface FindPosition extends Position {
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
bias?: number;
}
export interface SourceFindPosition extends FindPosition {
source: string;
}
export interface MappedPosition extends Position {
source: string;
name?: string;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export class SourceMapConsumer {
static GENERATED_ORDER: number;
static ORIGINAL_ORDER: number;
static GREATEST_LOWER_BOUND: number;
static LEAST_UPPER_BOUND: number;
constructor(rawSourceMap: RawSourceMap);
computeColumnSpans(): void;
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
hasContentsOfAllSources(): boolean;
sourceContentFor(source: string, returnNullOnMissing?: boolean): string;
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
addMapping(mapping: Mapping): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export class SourceNode {
constructor();
constructor(line: number, column: number, source: string);
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
add(chunk: string): void;
prepend(chunk: string): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

View File

@@ -0,0 +1,21 @@
MIT License
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:
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.

View File

@@ -0,0 +1,294 @@
<div align="center">
<img src="./logo/logo-web.svg" width="348.61" height="100" alt="SVGO logo"/>
</div>
## SVGO [![npm version](https://img.shields.io/npm/v/svgo)](https://npmjs.org/package/svgo) [![Discord](https://img.shields.io/discord/815166721315831868)](https://discord.gg/z8jX8NYxrE)
**SVG O**ptimizer is a Node.js-based tool for optimizing SVG vector graphics files.
## Why?
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.
## Installation
```sh
npm -g install svgo
```
or
```sh
yarn global add svgo
```
## CLI usage
```sh
svgo one.svg two.svg -o one.min.svg two.min.svg
```
Or use the `--folder`/`-f` flag to optimize a whole folder of SVG icons
```sh
svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output
```
See help for advanced usage
```sh
svgo --help
```
## Configuration
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.
```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 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:
```js
module.exports = {
plugins: [
// enable a built-in plugin by name
'prefixIds',
// or by expanded version
{
name: 'prefixIds',
},
// some plugins allow/require to pass options
{
name: 'prefixIds',
params: {
prefix: 'my-prefix',
},
},
],
};
```
The default preset of plugins is fully overridden if the `plugins` field is specified.
Use `preset-default` plugin to customize plugins options.
```js
module.exports = {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// customize options for plugins included in preset
inlineStyles: {
onlyMatchedOnce: false,
},
// or disable plugins
removeDoctype: false,
},
},
},
// enable builtin plugin not included in default preset
'prefixIds',
// enable and configure builtin plugin not included in preset
{
name: 'sortAttrs',
params: {
xmlnsOrder: 'alphabetical',
},
},
],
};
```
Default preset includes the following list of 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
It's also possible to specify a custom plugin:
```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,
],
};
```
## 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 [André Castillo](https://github.com/DerianAndre).

View File

@@ -0,0 +1,10 @@
#!/usr/bin/env node
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);
});

View File

@@ -0,0 +1,131 @@
{
"packageManager": "yarn@2.4.3",
"name": "svgo",
"version": "2.8.0",
"description": "Nodejs-based tool for optimizing SVG vector graphics files",
"license": "MIT",
"keywords": [
"svgo",
"svg",
"optimize",
"minify"
],
"homepage": "https://github.com/svg/svgo",
"bugs": {
"url": "https://github.com/svg/svgo/issues"
},
"author": {
"name": "Kir Belevich",
"email": "kir@belevi.ch",
"url": "https://github.com/deepsweet"
},
"contributors": [
{
"name": "Sergey Belov",
"email": "peimei@ya.ru",
"url": "https://github.com/arikon"
},
{
"name": "Lev Solntsev",
"email": "lev.sun@ya.ru",
"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-node.js",
"bin": "./bin/svgo",
"files": [
"bin",
"lib",
"plugins",
"dist",
"!**/*.test.js"
],
"engines": {
"node": ">=10.13.0"
},
"scripts": {
"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": {
"@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": {
"@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"
}
}

View 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;
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,816 @@
'use strict';
/**
* @typedef {import('../lib/types').XastElement} XastElement
* @typedef {import('../lib/types').PathDataItem} PathDataItem
*/
const { parsePathData, stringifyPathData } = require('../lib/path.js');
/**
* @type {[number, number]}
*/
var prevCtrlPoint;
/**
* Convert path string to JS representation.
*
* @type {(path: XastElement) => Array<PathDataItem>}
*/
const path2js = (path) => {
// @ts-ignore legacy
if (path.pathJS) return path.pathJS;
/**
* @type {Array<PathDataItem>}
*/
const pathData = []; // JS representation of the path data
const newPathData = parsePathData(path.attributes.d);
for (const { command, args } of newPathData) {
pathData.push({ command, args });
}
// First moveto is actually absolute. Subsequent coordinates were separated above.
if (pathData.length && pathData[0].command == 'm') {
pathData[0].command = 'M';
}
// @ts-ignore legacy
path.pathJS = pathData;
return pathData;
};
exports.path2js = path2js;
/**
* Convert relative Path data to absolute.
*
* @type {(data: Array<PathDataItem>) => Array<PathDataItem>}
*
*/
const convertRelativeToAbsolute = (data) => {
/**
* @type {Array<PathDataItem>}
*/
const newData = [];
let start = [0, 0];
let cursor = [0, 0];
for (let { command, args } of data) {
args = args.slice();
// moveto (x y)
if (command === 'm') {
args[0] += cursor[0];
args[1] += cursor[1];
command = 'M';
}
if (command === 'M') {
cursor[0] = args[0];
cursor[1] = args[1];
start[0] = cursor[0];
start[1] = cursor[1];
}
// horizontal lineto (x)
if (command === 'h') {
args[0] += cursor[0];
command = 'H';
}
if (command === 'H') {
cursor[0] = args[0];
}
// vertical lineto (y)
if (command === 'v') {
args[0] += cursor[1];
command = 'V';
}
if (command === 'V') {
cursor[1] = args[0];
}
// lineto (x y)
if (command === 'l') {
args[0] += cursor[0];
args[1] += cursor[1];
command = 'L';
}
if (command === 'L') {
cursor[0] = args[0];
cursor[1] = args[1];
}
// curveto (x1 y1 x2 y2 x y)
if (command === 'c') {
args[0] += cursor[0];
args[1] += cursor[1];
args[2] += cursor[0];
args[3] += cursor[1];
args[4] += cursor[0];
args[5] += cursor[1];
command = 'C';
}
if (command === 'C') {
cursor[0] = args[4];
cursor[1] = args[5];
}
// smooth curveto (x2 y2 x y)
if (command === 's') {
args[0] += cursor[0];
args[1] += cursor[1];
args[2] += cursor[0];
args[3] += cursor[1];
command = 'S';
}
if (command === 'S') {
cursor[0] = args[2];
cursor[1] = args[3];
}
// quadratic Bézier curveto (x1 y1 x y)
if (command === 'q') {
args[0] += cursor[0];
args[1] += cursor[1];
args[2] += cursor[0];
args[3] += cursor[1];
command = 'Q';
}
if (command === 'Q') {
cursor[0] = args[2];
cursor[1] = args[3];
}
// smooth quadratic Bézier curveto (x y)
if (command === 't') {
args[0] += cursor[0];
args[1] += cursor[1];
command = 'T';
}
if (command === 'T') {
cursor[0] = args[0];
cursor[1] = args[1];
}
// elliptical arc (rx ry x-axis-rotation large-arc-flag sweep-flag x y)
if (command === 'a') {
args[5] += cursor[0];
args[6] += cursor[1];
command = 'A';
}
if (command === 'A') {
cursor[0] = args[5];
cursor[1] = args[6];
}
// closepath
if (command === 'z' || command === 'Z') {
cursor[0] = start[0];
cursor[1] = start[1];
command = 'z';
}
newData.push({ command, args });
}
return newData;
};
/**
* @typedef {{ floatPrecision?: number, noSpaceAfterFlags?: boolean }} Js2PathParams
*/
/**
* Convert path array to string.
*
* @type {(path: XastElement, data: Array<PathDataItem>, params: Js2PathParams) => void}
*/
exports.js2path = function (path, data, params) {
// @ts-ignore legacy
path.pathJS = data;
const pathData = [];
for (const item of data) {
// remove moveto commands which are followed by moveto commands
if (
pathData.length !== 0 &&
(item.command === 'M' || item.command === 'm')
) {
const last = pathData[pathData.length - 1];
if (last.command === 'M' || last.command === 'm') {
pathData.pop();
}
}
pathData.push({
command: item.command,
args: item.args,
});
}
path.attributes.d = stringifyPathData({
pathData,
precision: params.floatPrecision,
disableSpaceAfterFlags: params.noSpaceAfterFlags,
});
};
/**
* @type {(dest: Array<number>, source: Array<number>) => Array<number>}
*/
function set(dest, source) {
dest[0] = source[source.length - 2];
dest[1] = source[source.length - 1];
return dest;
}
/**
* Checks if two paths have an intersection by checking convex hulls
* collision using Gilbert-Johnson-Keerthi distance algorithm
* https://web.archive.org/web/20180822200027/http://entropyinteractive.com/2011/04/gjk-algorithm/
*
* @type {(path1: Array<PathDataItem>, path2: Array<PathDataItem>) => boolean}
*/
exports.intersects = function (path1, path2) {
// Collect points of every subpath.
const points1 = gatherPoints(convertRelativeToAbsolute(path1));
const points2 = gatherPoints(convertRelativeToAbsolute(path2));
// Axis-aligned bounding box check.
if (
points1.maxX <= points2.minX ||
points2.maxX <= points1.minX ||
points1.maxY <= points2.minY ||
points2.maxY <= points1.minY ||
points1.list.every((set1) => {
return points2.list.every((set2) => {
return (
set1.list[set1.maxX][0] <= set2.list[set2.minX][0] ||
set2.list[set2.maxX][0] <= set1.list[set1.minX][0] ||
set1.list[set1.maxY][1] <= set2.list[set2.minY][1] ||
set2.list[set2.maxY][1] <= set1.list[set1.minY][1]
);
});
})
)
return false;
// Get a convex hull from points of each subpath. Has the most complexity O(n·log n).
const hullNest1 = points1.list.map(convexHull);
const hullNest2 = points2.list.map(convexHull);
// Check intersection of every subpath of the first path with every subpath of the second.
return hullNest1.some(function (hull1) {
if (hull1.list.length < 3) return false;
return hullNest2.some(function (hull2) {
if (hull2.list.length < 3) return false;
var simplex = [getSupport(hull1, hull2, [1, 0])], // create the initial simplex
direction = minus(simplex[0]); // set the direction to point towards the origin
var iterations = 1e4; // infinite loop protection, 10 000 iterations is more than enough
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-constant-condition
if (iterations-- == 0) {
console.error(
'Error: infinite loop while processing mergePaths plugin.'
);
return true; // true is the safe value that means “do nothing with paths”
}
// add a new point
simplex.push(getSupport(hull1, hull2, direction));
// see if the new point was on the correct side of the origin
if (dot(direction, simplex[simplex.length - 1]) <= 0) return false;
// process the simplex
if (processSimplex(simplex, direction)) return true;
}
});
});
/**
* @type {(a: Point, b: Point, direction: Array<number>) => Array<number>}
*/
function getSupport(a, b, direction) {
return sub(supportPoint(a, direction), supportPoint(b, minus(direction)));
}
// Computes farthest polygon point in particular direction.
// Thanks to knowledge of min/max x and y coordinates we can choose a quadrant to search in.
// Since we're working on convex hull, the dot product is increasing until we find the farthest point.
/**
* @type {(polygon: Point, direction: Array<number>) => Array<number>}
*/
function supportPoint(polygon, direction) {
var index =
direction[1] >= 0
? direction[0] < 0
? polygon.maxY
: polygon.maxX
: direction[0] < 0
? polygon.minX
: polygon.minY,
max = -Infinity,
value;
while ((value = dot(polygon.list[index], direction)) > max) {
max = value;
index = ++index % polygon.list.length;
}
return polygon.list[(index || polygon.list.length) - 1];
}
};
/**
* @type {(simplex: Array<Array<number>>, direction: Array<number>) => boolean}
*/
function processSimplex(simplex, direction) {
// we only need to handle to 1-simplex and 2-simplex
if (simplex.length == 2) {
// 1-simplex
let a = simplex[1],
b = simplex[0],
AO = minus(simplex[1]),
AB = sub(b, a);
// AO is in the same direction as AB
if (dot(AO, AB) > 0) {
// get the vector perpendicular to AB facing O
set(direction, orth(AB, a));
} else {
set(direction, AO);
// only A remains in the simplex
simplex.shift();
}
} else {
// 2-simplex
let a = simplex[2], // [a, b, c] = simplex
b = simplex[1],
c = simplex[0],
AB = sub(b, a),
AC = sub(c, a),
AO = minus(a),
ACB = orth(AB, AC), // the vector perpendicular to AB facing away from C
ABC = orth(AC, AB); // the vector perpendicular to AC facing away from B
if (dot(ACB, AO) > 0) {
if (dot(AB, AO) > 0) {
// region 4
set(direction, ACB);
simplex.shift(); // simplex = [b, a]
} else {
// region 5
set(direction, AO);
simplex.splice(0, 2); // simplex = [a]
}
} else if (dot(ABC, AO) > 0) {
if (dot(AC, AO) > 0) {
// region 6
set(direction, ABC);
simplex.splice(1, 1); // simplex = [c, a]
} else {
// region 5 (again)
set(direction, AO);
simplex.splice(0, 2); // simplex = [a]
}
} // region 7
else return true;
}
return false;
}
/**
* @type {(v: Array<number>) => Array<number>}
*/
function minus(v) {
return [-v[0], -v[1]];
}
/**
* @type {(v1: Array<number>, v2: Array<number>) => Array<number>}
*/
function sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
}
/**
* @type {(v1: Array<number>, v2: Array<number>) => number}
*/
function dot(v1, v2) {
return v1[0] * v2[0] + v1[1] * v2[1];
}
/**
* @type {(v1: Array<number>, v2: Array<number>) => Array<number>}
*/
function orth(v, from) {
var o = [-v[1], v[0]];
return dot(o, minus(from)) < 0 ? minus(o) : o;
}
/**
* @typedef {{
* list: Array<Array<number>>,
* minX: number,
* minY: number,
* maxX: number,
* maxY: number
* }} Point
*/
/**
* @typedef {{
* list: Array<Point>,
* minX: number,
* minY: number,
* maxX: number,
* maxY: number
* }} Points
*/
/**
* @type {(pathData: Array<PathDataItem>) => Points}
*/
function gatherPoints(pathData) {
/**
* @type {Points}
*/
const points = { list: [], minX: 0, minY: 0, maxX: 0, maxY: 0 };
// Writes data about the extreme points on each axle
/**
* @type {(path: Point, point: Array<number>) => void}
*/
const addPoint = (path, point) => {
if (!path.list.length || point[1] > path.list[path.maxY][1]) {
path.maxY = path.list.length;
points.maxY = points.list.length
? Math.max(point[1], points.maxY)
: point[1];
}
if (!path.list.length || point[0] > path.list[path.maxX][0]) {
path.maxX = path.list.length;
points.maxX = points.list.length
? Math.max(point[0], points.maxX)
: point[0];
}
if (!path.list.length || point[1] < path.list[path.minY][1]) {
path.minY = path.list.length;
points.minY = points.list.length
? Math.min(point[1], points.minY)
: point[1];
}
if (!path.list.length || point[0] < path.list[path.minX][0]) {
path.minX = path.list.length;
points.minX = points.list.length
? Math.min(point[0], points.minX)
: point[0];
}
path.list.push(point);
};
for (let i = 0; i < pathData.length; i += 1) {
const pathDataItem = pathData[i];
let subPath =
points.list.length === 0
? { list: [], minX: 0, minY: 0, maxX: 0, maxY: 0 }
: points.list[points.list.length - 1];
let prev = i === 0 ? null : pathData[i - 1];
let basePoint =
subPath.list.length === 0 ? null : subPath.list[subPath.list.length - 1];
let data = pathDataItem.args;
let ctrlPoint = basePoint;
/**
* @type {(n: number, i: number) => number}
* TODO fix null hack
*/
const toAbsolute = (n, i) => n + (basePoint == null ? 0 : basePoint[i % 2]);
switch (pathDataItem.command) {
case 'M':
subPath = { list: [], minX: 0, minY: 0, maxX: 0, maxY: 0 };
points.list.push(subPath);
break;
case 'H':
if (basePoint != null) {
addPoint(subPath, [data[0], basePoint[1]]);
}
break;
case 'V':
if (basePoint != null) {
addPoint(subPath, [basePoint[0], data[0]]);
}
break;
case 'Q':
addPoint(subPath, data.slice(0, 2));
prevCtrlPoint = [data[2] - data[0], data[3] - data[1]]; // Save control point for shorthand
break;
case 'T':
if (
basePoint != null &&
prev != null &&
(prev.command == 'Q' || prev.command == 'T')
) {
ctrlPoint = [
basePoint[0] + prevCtrlPoint[0],
basePoint[1] + prevCtrlPoint[1],
];
addPoint(subPath, ctrlPoint);
prevCtrlPoint = [data[0] - ctrlPoint[0], data[1] - ctrlPoint[1]];
}
break;
case 'C':
if (basePoint != null) {
// Approximate quibic Bezier curve with middle points between control points
addPoint(subPath, [
0.5 * (basePoint[0] + data[0]),
0.5 * (basePoint[1] + data[1]),
]);
}
addPoint(subPath, [
0.5 * (data[0] + data[2]),
0.5 * (data[1] + data[3]),
]);
addPoint(subPath, [
0.5 * (data[2] + data[4]),
0.5 * (data[3] + data[5]),
]);
prevCtrlPoint = [data[4] - data[2], data[5] - data[3]]; // Save control point for shorthand
break;
case 'S':
if (
basePoint != null &&
prev != null &&
(prev.command == 'C' || prev.command == 'S')
) {
addPoint(subPath, [
basePoint[0] + 0.5 * prevCtrlPoint[0],
basePoint[1] + 0.5 * prevCtrlPoint[1],
]);
ctrlPoint = [
basePoint[0] + prevCtrlPoint[0],
basePoint[1] + prevCtrlPoint[1],
];
}
if (ctrlPoint != null) {
addPoint(subPath, [
0.5 * (ctrlPoint[0] + data[0]),
0.5 * (ctrlPoint[1] + data[1]),
]);
}
addPoint(subPath, [
0.5 * (data[0] + data[2]),
0.5 * (data[1] + data[3]),
]);
prevCtrlPoint = [data[2] - data[0], data[3] - data[1]];
break;
case 'A':
if (basePoint != null) {
// Convert the arc to bezier curves and use the same approximation
// @ts-ignore no idea what's going on here
var curves = a2c.apply(0, basePoint.concat(data));
for (
var cData;
(cData = curves.splice(0, 6).map(toAbsolute)).length;
) {
if (basePoint != null) {
addPoint(subPath, [
0.5 * (basePoint[0] + cData[0]),
0.5 * (basePoint[1] + cData[1]),
]);
}
addPoint(subPath, [
0.5 * (cData[0] + cData[2]),
0.5 * (cData[1] + cData[3]),
]);
addPoint(subPath, [
0.5 * (cData[2] + cData[4]),
0.5 * (cData[3] + cData[5]),
]);
if (curves.length) addPoint(subPath, (basePoint = cData.slice(-2)));
}
}
break;
}
// Save final command coordinates
if (data.length >= 2) addPoint(subPath, data.slice(-2));
}
return points;
}
/**
* Forms a convex hull from set of points of every subpath using monotone chain convex hull algorithm.
* https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
*
* @type {(points: Point) => Point}
*/
function convexHull(points) {
points.list.sort(function (a, b) {
return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
});
var lower = [],
minY = 0,
bottom = 0;
for (let i = 0; i < points.list.length; i++) {
while (
lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], points.list[i]) <=
0
) {
lower.pop();
}
if (points.list[i][1] < points.list[minY][1]) {
minY = i;
bottom = lower.length;
}
lower.push(points.list[i]);
}
var upper = [],
maxY = points.list.length - 1,
top = 0;
for (let i = points.list.length; i--; ) {
while (
upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], points.list[i]) <=
0
) {
upper.pop();
}
if (points.list[i][1] > points.list[maxY][1]) {
maxY = i;
top = upper.length;
}
upper.push(points.list[i]);
}
// last points are equal to starting points of the other part
upper.pop();
lower.pop();
const hullList = lower.concat(upper);
/**
* @type {Point}
*/
const hull = {
list: hullList,
minX: 0, // by sorting
maxX: lower.length,
minY: bottom,
maxY: (lower.length + top) % hullList.length,
};
return hull;
}
/**
* @type {(o: Array<number>, a: Array<number>, b: Array<number>) => number}
*/
function cross(o, a, b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
/**
* Based on code from Snap.svg (Apache 2 license). http://snapsvg.io/
* Thanks to Dmitry Baranovskiy for his great work!
*
* @type {(
* x1: number,
* y1: number,
* rx: number,
* ry: number,
* angle: number,
* large_arc_flag: number,
* sweep_flag: number,
* x2: number,
* y2: number,
* recursive: Array<number>
* ) => Array<number>}
*/
const a2c = (
x1,
y1,
rx,
ry,
angle,
large_arc_flag,
sweep_flag,
x2,
y2,
recursive
) => {
// for more information of where this Math came from visit:
// https://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
const _120 = (Math.PI * 120) / 180;
const rad = (Math.PI / 180) * (+angle || 0);
/**
* @type {Array<number>}
*/
let res = [];
/**
* @type {(x: number, y: number, rad: number) => number}
*/
const rotateX = (x, y, rad) => {
return x * Math.cos(rad) - y * Math.sin(rad);
};
/**
* @type {(x: number, y: number, rad: number) => number}
*/
const rotateY = (x, y, rad) => {
return x * Math.sin(rad) + y * Math.cos(rad);
};
if (!recursive) {
x1 = rotateX(x1, y1, -rad);
y1 = rotateY(x1, y1, -rad);
x2 = rotateX(x2, y2, -rad);
y2 = rotateY(x2, y2, -rad);
var x = (x1 - x2) / 2,
y = (y1 - y2) / 2;
var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
if (h > 1) {
h = Math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
var rx2 = rx * rx;
var ry2 = ry * ry;
var k =
(large_arc_flag == sweep_flag ? -1 : 1) *
Math.sqrt(
Math.abs(
(rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)
)
);
var cx = (k * rx * y) / ry + (x1 + x2) / 2;
var cy = (k * -ry * x) / rx + (y1 + y2) / 2;
var f1 = Math.asin(Number(((y1 - cy) / ry).toFixed(9)));
var f2 = Math.asin(Number(((y2 - cy) / ry).toFixed(9)));
f1 = x1 < cx ? Math.PI - f1 : f1;
f2 = x2 < cx ? Math.PI - f2 : f2;
f1 < 0 && (f1 = Math.PI * 2 + f1);
f2 < 0 && (f2 = Math.PI * 2 + f2);
if (sweep_flag && f1 > f2) {
f1 = f1 - Math.PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - Math.PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
var df = f2 - f1;
if (Math.abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * Math.cos(f2);
y2 = cy + ry * Math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [
f2,
f2old,
cx,
cy,
]);
}
df = f2 - f1;
var c1 = Math.cos(f1),
s1 = Math.sin(f1),
c2 = Math.cos(f2),
s2 = Math.sin(f2),
t = Math.tan(df / 4),
hx = (4 / 3) * rx * t,
hy = (4 / 3) * ry * t,
m = [
-hx * s1,
hy * c1,
x2 + hx * s2 - x1,
y2 - hy * c2 - y1,
x2 - x1,
y2 - y1,
];
if (recursive) {
return m.concat(res);
} else {
res = m.concat(res);
var newres = [];
for (var i = 0, n = res.length; i < n; i++) {
newres[i] =
i % 2
? rotateY(res[i - 1], res[i], rad)
: rotateX(res[i], res[i + 1], rad);
}
return newres;
}
};

View File

@@ -0,0 +1,379 @@
'use strict';
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.
*
* @type {(transformString: string) => Array<TransformItem>}
*/
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 empty array if broken transform (no data)
return current == null || current.data.length == 0 ? [] : transforms;
};
/**
* Multiply transforms into one.
*
* @type {(transforms: Array<TransformItem>) => TransformItem}
*/
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;
};
/**
* math utilities in radians.
*/
const mth = {
/**
* @type {(deg: number) => number}
*/
rad: (deg) => {
return (deg * Math.PI) / 180;
},
/**
* @type {(rad: number) => number}
*/
deg: (rad) => {
return (rad * 180) / Math.PI;
},
/**
* @type {(deg: number) => number}
*/
cos: (deg) => {
return Math.cos(mth.rad(deg));
},
/**
* @type {(val: number, floatPrecision: number) => number}
*/
acos: (val, floatPrecision) => {
return Number(mth.deg(Math.acos(val)).toFixed(floatPrecision));
},
/**
* @type {(deg: number) => number}
*/
sin: (deg) => {
return Math.sin(mth.rad(deg));
},
/**
* @type {(val: number, floatPrecision: number) => number}
*/
asin: (val, floatPrecision) => {
return Number(mth.deg(Math.asin(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
* https://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
*
* @type {(transform: TransformItem, params: TransformParams) => Array<TransformItem>}
*/
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),
});
}
// [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];
// [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.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 (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 ? 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);
}
// 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;
};
/**
* Convert transform to the matrix data.
*
* @type {(transform: TransformItem) => Array<number> }
*/
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
* by the transformation matrix and use a singular value decomposition to represent in a form
* 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}})
*
* @type {(
* cursor: [x: number, y: number],
* arc: Array<number>,
* transform: Array<number>
* ) => Array<number>}
*/
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;
}
}
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 {
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.
*
* @type {(a: Array<number>, b: Array<number>) => Array<number>}
*/
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],
];
};

View 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];
}
}
}
}
}
},
},
};
};

View File

@@ -0,0 +1,87 @@
'use strict';
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.
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: [
* {
* name: "addClassesToSVGElement",
* params: {
* className: "mySvg"
* }
* }
* ]
*
* plugins: [
* {
* name: "addClassesToSVGElement",
* params: {
* classNames: ["mySvg", "size-big"]
* }
* }
* ]
*
* @author April Arcus
*
* @type {import('../lib/types').Plugin<{
* className?: string,
* classNames?: Array<string>
* }>}
*/
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(' ');
}
},
},
};
};

View File

@@ -0,0 +1,55 @@
'use strict';
exports.name = 'cleanupAttrs';
exports.type = 'visitor';
exports.active = true;
exports.description =
'cleanups attributes from newlines, trailing and repeating spaces';
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.
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* newlines?: boolean,
* trim?: boolean,
* spaces?: boolean
* }>}
*/
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,
' '
);
}
}
},
},
};
};

View File

@@ -0,0 +1,75 @@
'use strict';
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';
/**
* Remove or cleanup enable-background attr which coincides with a width/height box.
*
* @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">
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = (root) => {
const regEnableBackground =
/^new\s0\s0\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)\s([-+]?\d*\.?\d+([eE][-+]?\d+)?)$/;
let hasFilter = false;
visit(root, {
element: {
enter: (node) => {
if (node.name === 'filter') {
hasFilter = true;
}
},
},
});
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'];
}
},
},
};
};

View File

@@ -0,0 +1,297 @@
'use strict';
/**
* @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';
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;
/**
* Check if an ID starts with any one of a list of strings.
*
* @type {(string: string, prefixes: Array<string>) => boolean}
*/
const hasStringPrefix = (string, prefixes) => {
for (const prefix of prefixes) {
if (string.startsWith(prefix)) {
return true;
}
}
return false;
};
/**
* Generate unique minimal ID.
*
* @type {(currentID: null | Array<number>) => Array<number>}
*/
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;
};
/**
* Get string from generated ID array.
*
* @type {(arr: Array<number>, prefix: string) => string}
*/
const getIDstring = (arr, prefix) => {
return prefix + arr.map((i) => generateIDchars[i]).join('');
};
/**
* 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;
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;
}
// 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;
}
}
}
},
},
};
};

View File

@@ -0,0 +1,154 @@
'use strict';
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';
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,
};
/**
* Round list of values to the fixed precision.
*
* @example
* <svg viewBox="0 0 200.28423 200.28423" enable-background="new 0 0 200.28423 200.28423">
* ⬇
* <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 ... "/>
*
* @author kiyopikko
*
* @type {import('../lib/types').Plugin<{
* floatPrecision?: number,
* leadingZero?: boolean,
* defaultPx?: boolean,
* convertToPx?: boolean
* }>}
*/
exports.fn = (_root, params) => {
const {
floatPrecision = 3,
leadingZero = true,
defaultPx = true,
convertToPx = true,
} = params;
/**
* @type {(lists: string) => string}
*/
const roundValues = (lists) => {
const roundedList = [];
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);
}
}
return roundedList.join(' ');
};
return {
element: {
enter: (node) => {
if (node.attributes.points != null) {
node.attributes.points = roundValues(node.attributes.points);
}
if (node.attributes['enable-background'] != null) {
node.attributes['enable-background'] = roundValues(
node.attributes['enable-background']
);
}
if (node.attributes.viewBox != null) {
node.attributes.viewBox = roundValues(node.attributes.viewBox);
}
if (node.attributes['stroke-dasharray'] != null) {
node.attributes['stroke-dasharray'] = roundValues(
node.attributes['stroke-dasharray']
);
}
if (node.attributes.dx != null) {
node.attributes.dx = roundValues(node.attributes.dx);
}
if (node.attributes.dy != null) {
node.attributes.dy = roundValues(node.attributes.dy);
}
if (node.attributes.x != null) {
node.attributes.x = roundValues(node.attributes.x);
}
if (node.attributes.y != null) {
node.attributes.y = roundValues(node.attributes.y);
}
},
},
};
};

View File

@@ -0,0 +1,113 @@
'use strict';
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';
const regNumericValues =
/^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;
const absoluteLengths = {
// relative to px
cm: 96 / 2.54,
mm: 96 / 25.4,
in: 96,
pt: 4 / 3,
pc: 16,
px: 1,
};
/**
* Round numeric values to the fixed precision,
* remove default 'px' units.
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* floatPrecision?: number,
* leadingZero?: boolean,
* defaultPx?: boolean,
* convertToPx?: boolean
* }>}
*/
exports.fn = (_root, params) => {
const {
floatPrecision = 3,
leadingZero = true,
defaultPx = true,
convertToPx = true,
} = params;
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(' ');
}
for (const [name, value] of Object.entries(node.attributes)) {
// The `version` attribute is a text string and cannot be rounded
if (name === 'version') {
continue;
}
const match = value.match(regNumericValues);
// 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 = '';
}
node.attributes[name] = str + units;
}
}
},
},
};
};

View File

@@ -0,0 +1,135 @@
'use strict';
/**
* @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';
/**
* @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;
};
/**
* Collapse useless groups.
*
* @example
* <g>
* <g attr1="val1">
* <path d="..."/>
* </g>
* </g>
* ⬇
* <g>
* <g>
* <path attr1="val1" d="..."/>
* </g>
* </g>
* ⬇
* <path attr1="val1" d="..."/>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
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;
}
// 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;
}
}
},
},
};
};

View File

@@ -0,0 +1,152 @@
'use strict';
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';
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}$/;
/**
* 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 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:
* fuchsia ➡ #ff00ff
*
* Convert rgb() to long hex:
* rgb(255, 0, 255) ➡ #ff00ff
* rgb(50%, 100, 100%) ➡ #7f64ff
*
* Convert long hex to short hex:
* #aabbcc ➡ #abc
*
* Convert hex to short name
* #000080 ➡ navy
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* currentColor?: boolean | string | RegExp,
* names2hex?: boolean,
* rgb2hex?: boolean,
* shorthex?: boolean,
* shortname?: boolean,
* }>}
*/
exports.fn = (_root, params) => {
const {
currentColor = false,
names2hex = true,
rgb2hex = true,
shorthex = true,
shortname = true,
} = params;
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;
}
}
},
},
};
};

View 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;
}
}
},
},
};
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,175 @@
'use strict';
/**
* @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';
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 https://www.w3.org/TR/SVG11/shapes.html
*
* @author Lev Solntsev
*
* @type {import('../lib/types').Plugin<{
* convertArcs?: boolean,
* floatPrecision?: number
* }>}
*/
exports.fn = (root, params) => {
const { convertArcs = false, floatPrecision: precision } = params;
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;
}
// 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;
}
// 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;
}
// 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;
}
},
},
};
};

View File

@@ -0,0 +1,132 @@
'use strict';
exports.name = 'convertStyleToAttrs';
exports.type = 'perItem';
exports.active = false;
exports.description = 'converts style to attributes';
exports.params = {
keepImportant: false,
};
var stylingProps = require('./_collections').attrsGroups.presentation,
rEscape = '\\\\(?:[0-9a-f]{1,6}\\s?|\\r\\n|.)', // Like \" or \2051. Code points consume one space.
rAttr = '\\s*(' + g('[^:;\\\\]', rEscape) + '*?)\\s*', // attribute name like fill
rSingleQuotes = "'(?:[^'\\n\\r\\\\]|" + rEscape + ")*?(?:'|$)", // string in single quotes: 'smth'
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.
*
* @example
* <g style="fill:#000; color: #fff;">
* ⬇
* <g fill="#000" color="#fff">
*
* @example
* <g style="fill:#000; color: #fff; -webkit-blah: blah">
* ⬇
* <g fill="#000" color="#fff" style="-webkit-blah: blah">
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author Kir Belevich
*/
exports.fn = function (item, params) {
if (item.type === 'element' && item.attributes.style != null) {
// ['opacity: 1', 'color: #000']
let styles = [];
const newAttributes = {};
// 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, '|') + ')';
}

View File

@@ -0,0 +1,432 @@
'use strict';
/**
* @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';
/**
* 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 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 = (_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 (node.attributes.transform != null) {
convertTransform(node, 'transform', newParams);
}
// gradientTransform
if (node.attributes.gradientTransform != null) {
convertTransform(node, 'gradientTransform', newParams);
}
// patternTransform
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.
*
* @type {(item: XastElement, attrName: string, params: TransformParams) => void}
*/
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.convertToShorts) {
data = convertToShorts(data, params);
} else {
data.forEach((item) => roundTransform(item, params));
}
if (params.removeUseless) {
data = removeUseless(data);
}
if (data.length) {
item.attributes[attrName] = js2transform(data, params);
} else {
delete item.attributes[attrName];
}
};
/**
* Defines precision to work with certain parts.
* transformPrecision - for scale and four first matrix parameters (needs a better precision due to multiplying),
* floatPrecision - for translate including two last matrix and rotate parameters,
* degPrecision - for rotate and skew. By default it's equal to (rougly)
* transformPrecision - 2 or floatPrecision whichever is lower. Can be set in params.
*
* @type {(data: Array<TransformItem>, params: TransformParams) => TransformParams}
*
* clone params so it don't affect other elements transformations.
*/
const definePrecision = (data, { ...newParams }) => {
const matrixData = [];
for (const item of data) {
if (item.name == 'matrix') {
matrixData.push(...item.data.slice(0, 4));
}
}
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;
};
/**
* @type {(data: Array<number>, params: TransformParams) => Array<number>}
*/
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}
*/
const floatDigits = (n) => {
const str = n.toString();
return str.slice(str.indexOf('.')).length - 1;
};
/**
* Convert transforms to the shorthand alternatives.
*
* @type {(transforms: Array<TransformItem>, params: TransformParams) => Array<TransformItem>}
*/
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];
}
// 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.
*
* @type {(trasforms: Array<TransformItem>) => Array<TransformItem>}
*/
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 true;
});
};
/**
* Convert transforms JS representation to string.
*
* @type {(transformJS: Array<TransformItem>, params: TransformParams) => string}
*/
const js2transform = (transformJS, params) => {
var transformString = '';
// collect output value string
transformJS.forEach((transform) => {
roundTransform(transform, params);
transformString +=
(transformString && ' ') +
transform.name +
'(' +
cleanupOutData(transform.data, params) +
')';
});
return transformString;
};
/**
* @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.
*
* @type {(data: Array<number>) => Array<number>}
*/
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.
*
* @type {(precision: number, data: Array<number>) => Array<number>}
*/
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;
};

View 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);
}
}
}
},
},
};
};

View File

@@ -0,0 +1,104 @@
'use strict';
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';
/**
* Merge multiple Paths into one.
*
* @author Kir Belevich, Lev Solntsev
*
* @type {import('../lib/types').Plugin<{
* force?: boolean,
* floatPrecision?: number,
* noSpaceAfterFlags?: boolean
* }>}
*/
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);
return {
element: {
enter: (node) => {
let prevChild = 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;
}
// 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;
}
// preserve paths with markers
const computedStyle = computeStyle(stylesheet, child);
if (
computedStyle['marker-start'] ||
computedStyle['marker-mid'] ||
computedStyle['marker-end']
) {
prevChild = child;
continue;
}
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);
if (
attributesAreEqual &&
(force || !intersects(prevPathJS, curPathJS))
) {
js2path(prevChild, prevPathJS.concat(curPathJS), {
floatPrecision,
noSpaceAfterFlags,
});
detachNodeFromParent(child, node);
continue;
}
prevChild = child;
}
},
},
};
};

View 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
),
];
}
},
},
};
};

View File

@@ -0,0 +1,148 @@
'use strict';
/**
* @typedef {import('../lib/types').XastElement} XastElement
*/
const csso = require('csso');
exports.type = 'visitor';
exports.name = 'minifyStyles';
exports.active = true;
exports.description =
'minifies styles and removes unused styles based on usage data';
/**
* 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 = (_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();
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);
}
},
},
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;
}
},
},
};
};

View File

@@ -0,0 +1,130 @@
'use strict';
const { visit } = require('../lib/xast.js');
const { inheritableAttrs, pathElems } = require('./_collections.js');
exports.type = 'visitor';
exports.name = 'moveElemsAttrsToGroup';
exports.active = true;
exports.description = 'Move common attributes of group children to the group';
/**
* Move common attributes of group children to the group
*
* @example
* <g attr1="val1">
* <g attr2="val2">
* text
* </g>
* <circle attr2="val2" attr3="val3"/>
* </g>
* ⬇
* <g attr1="val1" attr2="val2">
* <g>
* text
* </g>
* <circle attr3="val3"/>
* </g>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
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);
}
}
}
}
}
// preserve transform on children when group has clip-path or mask
if (
node.attributes['clip-path'] != null ||
node.attributes.mask != null
) {
commonAttributes.delete('transform');
}
// preserve transform when all children are paths
// so the transform could be applied to path data by other plugins
if (everyChildIsPath) {
commonAttributes.delete('transform');
}
// 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];
}
}
}
},
},
};
};

View File

@@ -0,0 +1,62 @@
'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';
const pathElemsWithGroupsAndText = [...pathElems, 'g', 'text'];
/**
* Move group attrs to the content elements.
*
* @example
* <g transform="scale(2)">
* <path transform="rotate(45)" d="M0,0 L10,20"/>
* <path transform="translate(10, 20)" d="M0,10 L20,30"/>
* </g>
* ⬇
* <g>
* <path transform="scale(2) rotate(45)" d="M0,0 L10,20"/>
* <path transform="scale(2) translate(10, 20)" d="M0,10 L20,30"/>
* </g>
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author Kir Belevich
*/
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;
}
};

View 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');

View 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('; ');
}
}
},
},
};
};

View 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;

View 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 {};
};

View File

@@ -0,0 +1,159 @@
'use strict';
exports.name = 'removeAttrs';
exports.type = 'visitor';
exports.active = false;
exports.description = 'removes specified attributes';
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
*
* @example elemSeparator
* format: string
*
* @example preserveCurrentColor
* format: boolean
*
* @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:
*
* > basic: remove fill attribute
* ---
* removeAttrs:
* attrs: 'fill'
*
* > remove fill attribute on path element
* ---
* attrs: 'path:fill'
*
* > remove fill attribute on path element where value is none
* ---
* attrs: 'path:fill:none'
*
*
* > remove all fill and stroke attribute
* ---
* attrs:
* - 'fill'
* - 'stroke'
*
* [is same as]
*
* attrs: '(fill|stroke)'
*
* [is same as]
*
* attrs: '*:(fill|stroke)'
*
* [is same as]
*
* attrs: '.*:(fill|stroke)'
*
* [is same as]
*
* attrs: '.*:(fill|stroke):.*'
*
*
* > remove all stroke related attributes
* ----
* attrs: 'stroke.*'
*
*
* @author Benny Schudel
*
* @type {import('../lib/types').Plugin<{
* elemSeparator?: string,
* preserveCurrentColor?: boolean,
* attrs: string | Array<string>
* }>}
*/
exports.fn = (root, params) => {
if (typeof params.attrs == 'undefined') {
console.warn(ENOATTRS);
return null;
}
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];
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('');
}
// 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');
});
// 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];
}
}
}
}
},
},
};
};

View File

@@ -0,0 +1,31 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeComments';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes comments';
/**
* Remove comments.
*
* @example
* <!-- Generator: Adobe Illustrator 15.0.0, SVG Export
* Plug-In . SVG Version: 6.00 Build 0) -->
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = () => {
return {
comment: {
enter: (node, parentNode) => {
if (node.value.charAt(0) !== '!') {
detachNodeFromParent(node, parentNode);
}
},
},
};
};

View File

@@ -0,0 +1,41 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeDesc';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes <desc>';
const standardDescs = /^(Created with|Created using)/;
/**
* Removes <desc>.
* Removes only standard editors content or empty elements 'cause it can be used for accessibility.
* Enable parameter 'removeAny' to remove any description.
*
* https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc
*
* @author Daniel Wabyick
*
* @type {import('../lib/types').Plugin<{ removeAny?: boolean }>}
*/
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);
}
}
},
},
};
};

View File

@@ -0,0 +1,43 @@
'use strict';
exports.name = 'removeDimensions';
exports.type = 'perItem';
exports.active = false;
exports.description =
'removes width and height in presence of viewBox (opposite to removeViewBox, disable it first)';
/**
* Remove width/height attributes and add the viewBox attribute if it's missing
*
* @example
* <svg width="100" height="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.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
) {
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;
}
}
};

View File

@@ -0,0 +1,42 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeDoctype';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes doctype declaration';
/**
* Remove DOCTYPE declaration.
*
* "Unfortunately the SVG DTDs are a source of so many
* issues that the SVG WG has decided not to write one
* for the upcoming SVG 1.2 standard. In fact SVG WG
* members are even telling people not to use a DOCTYPE
* declaration in SVG 1.0 and 1.1 documents"
* https://jwatt.org/svg/authoring/#doctype-declaration
*
* @example
* <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
* q"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
*
* @example
* <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
* "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [
* <!-- an internal subset can be embedded here -->
* ]>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = () => {
return {
doctype: {
enter: (node, parentNode) => {
detachNodeFromParent(node, parentNode);
},
},
};
};

View File

@@ -0,0 +1,68 @@
'use strict';
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';
/**
* Remove editors namespaces, elements and attributes.
*
* @example
* <svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd">
* <sodipodi:namedview/>
* <path sodipodi:nodetypes="cccc"/>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* additionalNamespaces?: Array<string>
* }>}
*/
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];
}
}
}
// 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);
}
}
},
},
};
};

View 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;
}
}
}
},
},
};
};

View File

@@ -0,0 +1,33 @@
'use strict';
const { attrsGroups } = require('./_collections.js');
exports.type = 'visitor';
exports.name = 'removeEmptyAttrs';
exports.active = true;
exports.description = 'removes empty attributes';
/**
* Remove attributes with empty values.
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
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];
}
}
},
},
};
};

View File

@@ -0,0 +1,58 @@
'use strict';
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';
/**
* Remove empty containers.
*
* @see https://www.w3.org/TR/SVG11/intro.html#TermContainerElement
*
* @example
* <defs/>
*
* @example
* <g><marker><a/></marker></g>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
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);
},
},
};
};

View File

@@ -0,0 +1,57 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeEmptyText';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes empty <text> elements';
/**
* Remove empty Text elements.
*
* @see https://www.w3.org/TR/SVG11/text.html
*
* @example
* Remove empty text element:
* <text/>
*
* Remove empty tspan element:
* <tspan/>
*
* Remove tref with empty xlink:href attribute:
* <tref xlink:href=""/>
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* text?: boolean,
* tspan?: boolean,
* tref?: boolean
* }>}
*/
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);
}
},
},
};
};

View File

@@ -0,0 +1,318 @@
'use strict';
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)';
/**
* Remove hidden elements with disabled rendering:
* - display="none"
* - opacity="0"
* - circle with zero radius
* - ellipse with zero x-axis or y-axis radius
* - rectangle with zero width or height
* - pattern with zero width or height
* - image with zero width or height
* - path with empty data
* - polyline with empty points
* - polygon with empty points
*
* @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 = (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);
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"
//
// 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 (
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"
//
// https://www.w3.org/TR/SVG11/masking.html#ObjectAndGroupOpacityProperties
if (
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
//
// https://www.w3.org/TR/SVG11/shapes.html#CircleElementRAttribute
// "A value of zero disables rendering of the element"
//
// <circle r="0">
if (
circleR0 &&
node.name === 'circle' &&
node.children.length === 0 &&
node.attributes.r === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Ellipse with zero x-axis radius
//
// https://www.w3.org/TR/SVG11/shapes.html#EllipseElementRXAttribute
// "A value of zero disables rendering of the element"
//
// <ellipse rx="0">
if (
ellipseRX0 &&
node.name === 'ellipse' &&
node.children.length === 0 &&
node.attributes.rx === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Ellipse with zero y-axis radius
//
// https://www.w3.org/TR/SVG11/shapes.html#EllipseElementRYAttribute
// "A value of zero disables rendering of the element"
//
// <ellipse ry="0">
if (
ellipseRY0 &&
node.name === 'ellipse' &&
node.children.length === 0 &&
node.attributes.ry === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Rectangle with zero width
//
// https://www.w3.org/TR/SVG11/shapes.html#RectElementWidthAttribute
// "A value of zero disables rendering of the element"
//
// <rect width="0">
if (
rectWidth0 &&
node.name === 'rect' &&
node.children.length === 0 &&
node.attributes.width === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Rectangle with zero height
//
// https://www.w3.org/TR/SVG11/shapes.html#RectElementHeightAttribute
// "A value of zero disables rendering of the element"
//
// <rect height="0">
if (
rectHeight0 &&
rectWidth0 &&
node.name === 'rect' &&
node.children.length === 0 &&
node.attributes.height === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Pattern with zero width
//
// 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 (
patternWidth0 &&
node.name === 'pattern' &&
node.attributes.width === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Pattern with zero height
//
// 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 (
patternHeight0 &&
node.name === 'pattern' &&
node.attributes.height === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Image with zero width
//
// https://www.w3.org/TR/SVG11/struct.html#ImageElementWidthAttribute
// "A value of zero disables rendering of the element"
//
// <image width="0">
if (
imageWidth0 &&
node.name === 'image' &&
node.attributes.width === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Image with zero height
//
// https://www.w3.org/TR/SVG11/struct.html#ImageElementHeightAttribute
// "A value of zero disables rendering of the element"
//
// <image height="0">
if (
imageHeight0 &&
node.name === 'image' &&
node.attributes.height === '0'
) {
detachNodeFromParent(node, parentNode);
return;
}
// Path with empty data
//
// https://www.w3.org/TR/SVG11/paths.html#DAttribute
//
// <path d=""/>
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
//
// https://www.w3.org/TR/SVG11/shapes.html#PolylineElementPointsAttribute
//
// <polyline points="">
if (
polylineEmptyPoints &&
node.name === 'polyline' &&
node.attributes.points == null
) {
detachNodeFromParent(node, parentNode);
return;
}
// Polygon with empty points
//
// https://www.w3.org/TR/SVG11/shapes.html#PolygonElementPointsAttribute
//
// <polygon points="">
if (
polygonEmptyPoints &&
node.name === 'polygon' &&
node.attributes.points == null
) {
detachNodeFromParent(node, parentNode);
return;
}
},
},
};
};

View File

@@ -0,0 +1,29 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeMetadata';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes <metadata>';
/**
* Remove <metadata>.
*
* https://www.w3.org/TR/SVG11/metadata.html
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = () => {
return {
element: {
enter: (node, parentNode) => {
if (node.name === 'metadata') {
detachNodeFromParent(node, parentNode);
}
},
},
};
};

View File

@@ -0,0 +1,38 @@
'use strict';
exports.name = 'removeNonInheritableGroupAttrs';
exports.type = 'perItem';
exports.active = true;
exports.description =
'removes non-inheritable groups presentational attributes';
const {
inheritableAttrs,
attrsGroups,
presentationNonInheritableGroupAttrs,
} = require('./_collections');
/**
* Remove non-inheritable group's "presentation" attributes.
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author Kir Belevich
*/
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];
}
}
}
};

View 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);
}
}
},
},
};
};

View File

@@ -0,0 +1,33 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeRasterImages';
exports.type = 'visitor';
exports.active = false;
exports.description = 'removes raster images (disabled by default)';
/**
* Remove raster images references in <image>.
*
* @see https://bugs.webkit.org/show_bug.cgi?id=63548
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<void>}
*/
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);
}
},
},
};
};

View 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);
}
},
},
};
};

View File

@@ -0,0 +1,29 @@
'use strict';
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>.
*
* https://www.w3.org/TR/SVG11/styling.html#StyleElement
*
* @author Betsy Dupuis
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = () => {
return {
element: {
enter: (node, parentNode) => {
if (node.name === 'style') {
detachNodeFromParent(node, parentNode);
}
},
},
};
};

View File

@@ -0,0 +1,29 @@
'use strict';
const { detachNodeFromParent } = require('../lib/xast.js');
exports.name = 'removeTitle';
exports.type = 'visitor';
exports.active = true;
exports.description = 'removes <title>';
/**
* Remove <title>.
*
* https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title
*
* @author Igor Kalashnikov
*
* @type {import('../lib/types').Plugin<void>}
*/
exports.fn = () => {
return {
element: {
enter: (node, parentNode) => {
if (node.name === 'title') {
detachNodeFromParent(node, parentNode);
}
},
},
};
};

View File

@@ -0,0 +1,218 @@
'use strict';
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';
// resolve all groups references
/**
* @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 (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.
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* unknownContent?: boolean,
* unknownAttrs?: boolean,
* defaultAttrs?: boolean,
* uselessOverrides?: boolean,
* keepDataAttrs?: boolean,
* keepAriaAttrs?: boolean,
* keepRoleAttr?: boolean,
* }>}
*/
exports.fn = (root, params) => {
const {
unknownContent = true,
unknownAttrs = true,
defaultAttrs = true,
uselessOverrides = true,
keepDataAttrs = true,
keepAriaAttrs = true,
keepRoleAttr = false,
} = params;
const stylesheet = collectStylesheet(root);
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 (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
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];
}
}
}
},
},
};
};

View File

@@ -0,0 +1,61 @@
'use strict';
exports.type = 'visitor';
exports.name = 'removeUnusedNS';
exports.active = true;
exports.description = 'removes unused namespaces declaration';
/**
* 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 = () => {
/**
* @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 (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}`];
}
}
},
},
};
};

View File

@@ -0,0 +1,65 @@
'use strict';
/**
* @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';
/**
* Removes content of defs and properties that aren't rendered directly without ids.
*
* @author Lev Solntsev
*
* @type {import('../lib/types').Plugin<void>}
*/
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);
}
},
},
};
};
/**
* @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);
}
}
}
};

View File

@@ -0,0 +1,144 @@
'use strict';
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';
/**
* Remove useless stroke and fill attrs.
*
* @author Kir Belevich
*
* @type {import('../lib/types').Plugin<{
* stroke?: boolean,
* fill?: boolean,
* removeNone?: boolean
* }>}
*/
exports.fn = (root, params) => {
const {
stroke: removeStroke = true,
fill: removeFill = true,
removeNone = false,
} = params;
// 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;
}
const stylesheet = collectStylesheet(root);
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 (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];
}
}
// set explicit none to not inherit from parent
if (
parentStroke != null &&
parentStroke.type === 'static' &&
parentStroke.value !== 'none'
) {
node.attributes.stroke = 'none';
}
}
}
}
// remove 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);
}
}
},
},
};
};

Some files were not shown because too many files have changed in this diff Show More