first commit

This commit is contained in:
2026-09-08 20:28:54 +08:00
commit 2ada8d3d5a
37380 changed files with 4886169 additions and 0 deletions
+22
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.
+72
View File
@@ -0,0 +1,72 @@
# [postcss][postcss]-ordered-values
> Ensure values are ordered consistently in your CSS.
## Install
With [npm](https://npmjs.org/package/postcss-ordered-values) do:
```
npm install postcss-ordered-values --save
```
## Example
Some CSS properties accept their values in an arbitrary order; for this reason,
it is entirely possible that different developers will write their values in
different orders. This module normalizes the order, making it easier for other
modules to understand which declarations are duplicates.
### Input
```css
h1 {
border: solid 1px red;
border: red solid .5em;
border: rgba(0, 30, 105, 0.8) solid 1px;
border: 1px solid red;
}
```
### Output
```css
h1 {
border: 1px solid red;
border: .5em solid red;
border: 1px solid rgba(0, 30, 105, 0.8);
border: 1px solid red;
}
```
## Support List
For more examples, see the [tests](src/__tests__/index.js).
* `animation`, `-webkit-animation`
* `border(border-left|right|top|bottom)`
* `box-shadow`
* `outline`
* `flex-flow`
* `transition`, `-webkit-transition`
## 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
@@ -0,0 +1,22 @@
Copyright (c) Bogdan Chadkin <trysound@yandex.ru>
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.
@@ -0,0 +1,263 @@
# postcss-value-parser
[![Travis CI](https://travis-ci.org/TrySound/postcss-value-parser.svg)](https://travis-ci.org/TrySound/postcss-value-parser)
Transforms CSS declaration values and at-rule parameters into a tree of nodes, and provides a simple traversal API.
## Usage
```js
var valueParser = require('postcss-value-parser');
var cssBackgroundValue = 'url(foo.png) no-repeat 40px 73%';
var parsedValue = valueParser(cssBackgroundValue);
// parsedValue exposes an API described below,
// e.g. parsedValue.walk(..), parsedValue.toString(), etc.
```
For example, parsing the value `rgba(233, 45, 66, .5)` will return the following:
```js
{
nodes: [
{
type: 'function',
value: 'rgba',
before: '',
after: '',
nodes: [
{ type: 'word', value: '233' },
{ type: 'div', value: ',', before: '', after: ' ' },
{ type: 'word', value: '45' },
{ type: 'div', value: ',', before: '', after: ' ' },
{ type: 'word', value: '66' },
{ type: 'div', value: ',', before: ' ', after: '' },
{ type: 'word', value: '.5' }
]
}
]
}
```
If you wanted to convert each `rgba()` value in `sourceCSS` to a hex value, you could do so like this:
```js
var valueParser = require('postcss-value-parser');
var parsed = valueParser(sourceCSS);
// walk() will visit all the of the nodes in the tree,
// invoking the callback for each.
parsed.walk(function (node) {
// Since we only want to transform rgba() values,
// we can ignore anything else.
if (node.type !== 'function' && node.value !== 'rgba') return;
// We can make an array of the rgba() arguments to feed to a
// convertToHex() function
var color = node.nodes.filter(function (node) {
return node.type === 'word';
}).map(function (node) {
return Number(node.value);
}); // [233, 45, 66, .5]
// Now we will transform the existing rgba() function node
// into a word node with the hex value
node.type = 'word';
node.value = convertToHex(color);
})
parsed.toString(); // #E92D42
```
## Nodes
Each node is an object with these common properties:
- **type**: The type of node (`word`, `string`, `div`, `space`, `comment`, or `function`).
Each type is documented below.
- **value**: Each node has a `value` property; but what exactly `value` means
is specific to the node type. Details are documented for each type below.
- **sourceIndex**: The starting index of the node within the original source
string. For example, given the source string `10px 20px`, the `word` node
whose value is `20px` will have a `sourceIndex` of `5`.
### word
The catch-all node type that includes keywords (e.g. `no-repeat`),
quantities (e.g. `20px`, `75%`, `1.5`), and hex colors (e.g. `#e6e6e6`).
Node-specific properties:
- **value**: The "word" itself.
### string
A quoted string value, e.g. `"something"` in `content: "something";`.
Node-specific properties:
- **value**: The text content of the string.
- **quote**: The quotation mark surrounding the string, either `"` or `'`.
- **unclosed**: `true` if the string was not closed properly. e.g. `"unclosed string `.
### div
A divider, for example
- `,` in `animation-duration: 1s, 2s, 3s`
- `/` in `border-radius: 10px / 23px`
- `:` in `(min-width: 700px)`
Node-specific properties:
- **value**: The divider character. Either `,`, `/`, or `:` (see examples above).
- **before**: Whitespace before the divider.
- **after**: Whitespace after the divider.
### space
Whitespace used as a separator, e.g. ` ` occurring twice in `border: 1px solid black;`.
Node-specific properties:
- **value**: The whitespace itself.
### comment
A CSS comment starts with `/*` and ends with `*/`
Node-specific properties:
- **value**: The comment value without `/*` and `*/`
- **unclosed**: `true` if the comment was not closed properly. e.g. `/* comment without an end `.
### function
A CSS function, e.g. `rgb(0,0,0)` or `url(foo.bar)`.
Function nodes have nodes nested within them: the function arguments.
Additional properties:
- **value**: The name of the function, e.g. `rgb` in `rgb(0,0,0)`.
- **before**: Whitespace after the opening parenthesis and before the first argument,
e.g. ` ` in `rgb( 0,0,0)`.
- **after**: Whitespace before the closing parenthesis and after the last argument,
e.g. ` ` in `rgb(0,0,0 )`.
- **nodes**: More nodes representing the arguments to the function.
- **unclosed**: `true` if the parentheses was not closed properly. e.g. `( unclosed-function `.
Media features surrounded by parentheses are considered functions with an
empty value. For example, `(min-width: 700px)` parses to these nodes:
```js
[
{
type: 'function', value: '', before: '', after: '',
nodes: [
{ type: 'word', value: 'min-width' },
{ type: 'div', value: ':', before: '', after: ' ' },
{ type: 'word', value: '700px' }
]
}
]
```
`url()` functions can be parsed a little bit differently depending on
whether the first character in the argument is a quotation mark.
`url( /gfx/img/bg.jpg )` parses to:
```js
{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [
{ type: 'word', sourceIndex: 5, value: '/gfx/img/bg.jpg' }
] }
```
`url( "/gfx/img/bg.jpg" )`, on the other hand, parses to:
```js
{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [
type: 'string', sourceIndex: 5, quote: '"', value: '/gfx/img/bg.jpg' },
] }
```
### unicode-range
The unicode-range CSS descriptor sets the specific range of characters to be
used from a font defined by @font-face and made available
for use on the current page (`unicode-range: U+0025-00FF`).
Node-specific properties:
- **value**: The "unicode-range" itself.
## API
```
var valueParser = require('postcss-value-parser');
```
### valueParser.unit(quantity)
Parses `quantity`, distinguishing the number from the unit. Returns an object like the following:
```js
// Given 2rem
{
number: '2',
unit: 'rem'
}
```
If the `quantity` argument cannot be parsed as a number, returns `false`.
*This function does not parse complete values*: you cannot pass it `1px solid black` and expect `px` as
the unit. Instead, you should pass it single quantities only. Parse `1px solid black`, then pass it
the stringified `1px` node (a `word` node) to parse the number and unit.
### valueParser.stringify(nodes[, custom])
Stringifies a node or array of nodes.
The `custom` function is called for each `node`; return a string to override the default behaviour.
### valueParser.walk(nodes, callback[, bubble])
Walks each provided node, recursively walking all descendent nodes within functions.
Returning `false` in the `callback` will prevent traversal of descendent nodes (within functions).
You can use this feature to for shallow iteration, walking over only the *immediate* children.
*Note: This only applies if `bubble` is `false` (which is the default).*
By default, the tree is walked from the outermost node inwards.
To reverse the direction, pass `true` for the `bubble` argument.
The `callback` is invoked with three arguments: `callback(node, index, nodes)`.
- `node`: The current node.
- `index`: The index of the current node.
- `nodes`: The complete nodes array passed to `walk()`.
Returns the `valueParser` instance.
### var parsed = valueParser(value)
Returns the parsed node tree.
### parsed.nodes
The array of nodes.
### parsed.toString()
Stringifies the node tree.
### parsed.walk(callback[, bubble])
Walks each node inside `parsed.nodes`. See the documentation for `valueParser.walk()` above.
# License
MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru)
@@ -0,0 +1,177 @@
declare namespace postcssValueParser {
interface BaseNode {
/**
* The offset, inclusive, inside the CSS value at which the node starts.
*/
sourceIndex: number;
/**
* The offset, exclusive, inside the CSS value at which the node ends.
*/
sourceEndIndex: number;
/**
* The node's characteristic value
*/
value: string;
}
interface ClosableNode {
/**
* Whether the parsed CSS value ended before the node was properly closed
*/
unclosed?: true;
}
interface AdjacentAwareNode {
/**
* The token at the start of the node
*/
before: string;
/**
* The token at the end of the node
*/
after: string;
}
interface CommentNode extends BaseNode, ClosableNode {
type: "comment";
}
interface DivNode extends BaseNode, AdjacentAwareNode {
type: "div";
}
interface FunctionNode extends BaseNode, ClosableNode, AdjacentAwareNode {
type: "function";
/**
* Nodes inside the function
*/
nodes: Node[];
}
interface SpaceNode extends BaseNode {
type: "space";
}
interface StringNode extends BaseNode, ClosableNode {
type: "string";
/**
* The quote type delimiting the string
*/
quote: '"' | "'";
}
interface UnicodeRangeNode extends BaseNode {
type: "unicode-range";
}
interface WordNode extends BaseNode {
type: "word";
}
/**
* Any node parsed from a CSS value
*/
type Node =
| CommentNode
| DivNode
| FunctionNode
| SpaceNode
| StringNode
| UnicodeRangeNode
| WordNode;
interface CustomStringifierCallback {
/**
* @param node The node to stringify
* @returns The serialized CSS representation of the node
*/
(nodes: Node): string | undefined;
}
interface WalkCallback {
/**
* @param node The currently visited node
* @param index The index of the node in the series of parsed nodes
* @param nodes The series of parsed nodes
* @returns Returning `false` will prevent traversal of descendant nodes (only applies if `bubble` was set to `true` in the `walk()` call)
*/
(node: Node, index: number, nodes: Node[]): void | boolean;
}
/**
* A CSS dimension, decomposed into its numeric and unit parts
*/
interface Dimension {
number: string;
unit: string;
}
/**
* A wrapper around a parsed CSS value that allows for inspecting and walking nodes
*/
interface ParsedValue {
/**
* The series of parsed nodes
*/
nodes: Node[];
/**
* Walk all parsed nodes, applying a callback
*
* @param callback A visitor callback that will be executed for each node
* @param bubble When set to `true`, walking will be done inside-out instead of outside-in
*/
walk(callback: WalkCallback, bubble?: boolean): this;
}
interface ValueParser {
/**
* Decompose a CSS dimension into its numeric and unit part
*
* @param value The dimension to decompose
* @returns An object representing `number` and `unit` part of the dimension or `false` if the decomposing fails
*/
unit(value: string): Dimension | false;
/**
* Serialize a series of nodes into a CSS value
*
* @param nodes The nodes to stringify
* @param custom A custom stringifier callback
* @returns The generated CSS value
*/
stringify(nodes: Node | Node[], custom?: CustomStringifierCallback): string;
/**
* Walk a series of nodes, applying a callback
*
* @param nodes The nodes to walk
* @param callback A visitor callback that will be executed for each node
* @param bubble When set to `true`, walking will be done inside-out instead of outside-in
*/
walk(nodes: Node[], callback: WalkCallback, bubble?: boolean): void;
/**
* Parse a CSS value into a series of nodes to operate on
*
* @param value The value to parse
*/
new (value: string): ParsedValue;
/**
* Parse a CSS value into a series of nodes to operate on
*
* @param value The value to parse
*/
(value: string): ParsedValue;
}
}
declare const postcssValueParser: postcssValueParser.ValueParser;
export = postcssValueParser;
@@ -0,0 +1,28 @@
var parse = require("./parse");
var walk = require("./walk");
var stringify = require("./stringify");
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function() {
return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
};
ValueParser.prototype.walk = function(cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = require("./unit");
ValueParser.walk = walk;
ValueParser.stringify = stringify;
module.exports = ValueParser;
@@ -0,0 +1,321 @@
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = "\\".charCodeAt(0);
var slash = "/".charCodeAt(0);
var comma = ",".charCodeAt(0);
var colon = ":".charCodeAt(0);
var star = "*".charCodeAt(0);
var uLower = "u".charCodeAt(0);
var uUpper = "U".charCodeAt(0);
var plus = "+".charCodeAt(0);
var isUnicodeRange = /^[a-f0-9?-]+$/i;
module.exports = function(input) {
var tokens = [];
var value = input;
var next,
quote,
prev,
token,
escape,
escapePos,
whitespacePos,
parenthesesOpenPos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === "div") {
prev.after = token;
prev.sourceEndIndex += token.length;
} else if (
code === comma ||
code === colon ||
(code === slash &&
value.charCodeAt(next + 1) !== star &&
(!parent ||
(parent && parent.type === "function" && parent.value !== "calc")))
) {
before = token;
} else {
tokens.push({
type: "space",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? "'" : '"';
token = {
type: "string",
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
token.sourceEndIndex = token.unclosed ? next : next + 1;
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
next = value.indexOf("*/", pos);
token = {
type: "comment",
sourceIndex: pos,
sourceEndIndex: next + 2
};
if (next === -1) {
token.unclosed = true;
next = value.length;
token.sourceEndIndex = next;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Operation within calc
} else if (
(code === slash || code === star) &&
parent &&
parent.type === "function" &&
parent.value === "calc"
) {
token = value[pos];
tokens.push({
type: "word",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token
});
pos += 1;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: "div",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token,
before: before,
after: ""
});
before = "";
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
parenthesesOpenPos = pos;
token = {
type: "function",
sourceIndex: pos - name.length,
value: name,
before: value.slice(parenthesesOpenPos + 1, next)
};
pos = next;
if (name === "url" && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(")", next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ")";
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (parenthesesOpenPos < whitespacePos) {
if (pos !== whitespacePos + 1) {
token.nodes = [
{
type: "word",
sourceIndex: pos,
sourceEndIndex: whitespacePos + 1,
value: value.slice(pos, whitespacePos + 1)
}
];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = "";
token.nodes.push({
type: "space",
sourceIndex: whitespacePos + 1,
sourceEndIndex: next,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
token.sourceEndIndex = next;
}
} else {
token.after = "";
token.nodes = [];
}
pos = next + 1;
token.sourceEndIndex = token.unclosed ? next : pos;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = "";
token.sourceEndIndex = pos + 1;
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = "";
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
parent.sourceEndIndex += after.length;
after = "";
balanced -= 1;
stack[stack.length - 1].sourceEndIndex = pos;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (
next < max &&
!(
code <= 32 ||
code === singleQuote ||
code === doubleQuote ||
code === comma ||
code === colon ||
code === slash ||
code === openParentheses ||
(code === star &&
parent &&
parent.type === "function" &&
parent.value === "calc") ||
(code === slash &&
parent.type === "function" &&
parent.value === "calc") ||
(code === closeParentheses && balanced)
)
);
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else if (
(uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
plus === token.charCodeAt(1) &&
isUnicodeRange.test(token.slice(2))
) {
tokens.push({
type: "unicode-range",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
} else {
tokens.push({
type: "word",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
stack[pos].sourceEndIndex = value.length;
}
return stack[0].nodes;
};
@@ -0,0 +1,48 @@
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === "word" || type === "space") {
return value;
} else if (type === "string") {
buf = node.quote || "";
return buf + value + (node.unclosed ? "" : buf);
} else if (type === "comment") {
return "/*" + value + (node.unclosed ? "" : "*/");
} else if (type === "div") {
return (node.before || "") + value + (node.after || "");
} else if (Array.isArray(node.nodes)) {
buf = stringify(node.nodes, custom);
if (type !== "function") {
return buf;
}
return (
value +
"(" +
(node.before || "") +
buf +
(node.after || "") +
(node.unclosed ? "" : ")")
);
}
return value;
}
function stringify(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = "";
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
module.exports = stringify;
@@ -0,0 +1,120 @@
var minus = "-".charCodeAt(0);
var plus = "+".charCodeAt(0);
var dot = ".".charCodeAt(0);
var exp = "e".charCodeAt(0);
var EXP = "E".charCodeAt(0);
// Check if three code points would start a number
// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
function likeNumber(value) {
var code = value.charCodeAt(0);
var nextCode;
if (code === plus || code === minus) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
var nextNextCode = value.charCodeAt(2);
if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
return true;
}
return false;
}
if (code === dot) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
return false;
}
if (code >= 48 && code <= 57) {
return true;
}
return false;
}
// Consume a number
// https://www.w3.org/TR/css-syntax-3/#consume-number
module.exports = function(value) {
var pos = 0;
var length = value.length;
var code;
var nextCode;
var nextNextCode;
if (length === 0 || !likeNumber(value)) {
return false;
}
code = value.charCodeAt(pos);
if (code === plus || code === minus) {
pos++;
}
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
if (code === dot && nextCode >= 48 && nextCode <= 57) {
pos += 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
nextNextCode = value.charCodeAt(pos + 2);
if (
(code === exp || code === EXP) &&
((nextCode >= 48 && nextCode <= 57) ||
((nextCode === plus || nextCode === minus) &&
nextNextCode >= 48 &&
nextNextCode <= 57))
) {
pos += nextCode === plus || nextCode === minus ? 3 : 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
return {
number: value.slice(0, pos),
unit: value.slice(pos)
};
};
@@ -0,0 +1,22 @@
module.exports = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (
result !== false &&
node.type === "function" &&
Array.isArray(node.nodes)
) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
@@ -0,0 +1,58 @@
{
"name": "postcss-value-parser",
"version": "4.2.0",
"description": "Transforms css values and at-rule params into the tree",
"main": "lib/index.js",
"files": [
"lib"
],
"devDependencies": {
"eslint": "^5.16.0",
"husky": "^2.3.0",
"lint-staged": "^8.1.7",
"prettier": "^1.17.1",
"tap-spec": "^5.0.0",
"tape": "^4.10.2"
},
"scripts": {
"lint:prettier": "prettier \"**/*.js\" \"**/*.ts\" --list-different",
"lint:js": "eslint . --cache",
"lint": "yarn lint:js && yarn lint:prettier",
"pretest": "yarn lint",
"test": "tape test/*.js | tap-spec"
},
"eslintConfig": {
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended"
},
"lint-staged": {
"*.js": [
"eslint",
"prettier --write",
"git add"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"author": "Bogdan Chadkin <trysound@yandex.ru>",
"license": "MIT",
"homepage": "https://github.com/TrySound/postcss-value-parser",
"repository": {
"type": "git",
"url": "https://github.com/TrySound/postcss-value-parser.git"
},
"keywords": [
"postcss",
"value",
"parser"
],
"bugs": {
"url": "https://github.com/TrySound/postcss-value-parser/issues"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"name": "postcss-ordered-values",
"version": "5.1.3",
"description": "Ensure values are ordered consistently in your CSS.",
"main": "src/index.js",
"types": "types/index.d.ts",
"files": [
"src",
"LICENSE-MIT",
"types"
],
"keywords": [
"css",
"postcss",
"postcss-plugin"
],
"license": "MIT",
"homepage": "https://github.com/cssnano/cssnano",
"author": {
"name": "Ben Briggs",
"email": "beneb.info@gmail.com",
"url": "http://beneb.info"
},
"repository": "cssnano/cssnano",
"dependencies": {
"cssnano-utils": "^3.1.0",
"postcss-value-parser": "^4.2.0"
},
"bugs": {
"url": "https://github.com/cssnano/cssnano/issues"
},
"engines": {
"node": "^10 || ^12 || >=14.0"
},
"devDependencies": {
"postcss": "^8.2.15",
"undici": "^5.0.0"
},
"peerDependencies": {
"postcss": "^8.2.15"
}
}
+163
View File
@@ -0,0 +1,163 @@
'use strict';
const valueParser = require('postcss-value-parser');
const {
normalizeGridAutoFlow,
normalizeGridColumnRowGap,
normalizeGridColumnRow,
} = require('./rules/grid');
// rules
const animation = require('./rules/animation');
const border = require('./rules/border');
const boxShadow = require('./rules/boxShadow');
const flexFlow = require('./rules/flexFlow');
const transition = require('./rules/transition');
const listStyle = require('./rules/listStyle');
const column = require('./rules/columns');
const vendorUnprefixed = require('./lib/vendorUnprefixed.js');
/** @type {[string, (parsed: valueParser.ParsedValue) => string][]} */
const borderRules = [
['border', border],
['border-block', border],
['border-inline', border],
['border-block-end', border],
['border-block-start', border],
['border-inline-end', border],
['border-inline-start', border],
['border-top', border],
['border-right', border],
['border-bottom', border],
['border-left', border],
];
/** @type {[string, (parsed: valueParser.ParsedValue) => string | string[] | valueParser.ParsedValue][]} */
const grid = [
['grid-auto-flow', normalizeGridAutoFlow],
['grid-column-gap', normalizeGridColumnRowGap], // normal | <length-percentage>
['grid-row-gap', normalizeGridColumnRowGap], // normal | <length-percentage>
['grid-column', normalizeGridColumnRow], // <grid-line>+
['grid-row', normalizeGridColumnRow], // <grid-line>+
['grid-row-start', normalizeGridColumnRow], // <grid-line>
['grid-row-end', normalizeGridColumnRow], // <grid-line>
['grid-column-start', normalizeGridColumnRow], // <grid-line>
['grid-column-end', normalizeGridColumnRow], // <grid-line>
];
/** @type {[string, (parsed: valueParser.ParsedValue) => string | valueParser.ParsedValue][]} */
const columnRules = [
['column-rule', border],
['columns', column],
];
/** @type {Map<string, ((parsed: valueParser.ParsedValue) => string | string[] | valueParser.ParsedValue)>} */
const rules = new Map([
['animation', animation],
['outline', border],
['box-shadow', boxShadow],
['flex-flow', flexFlow],
['list-style', listStyle],
['transition', transition],
...borderRules,
...grid,
...columnRules,
]);
const variableFunctions = new Set(['var', 'env', 'constant']);
/**
* @param {valueParser.Node} node
* @return {boolean}
*/
function isVariableFunctionNode(node) {
if (node.type !== 'function') {
return false;
}
return variableFunctions.has(node.value.toLowerCase());
}
/**
* @param {valueParser.ParsedValue} parsed
* @return {boolean}
*/
function shouldAbort(parsed) {
let abort = false;
parsed.walk((node) => {
if (
node.type === 'comment' ||
isVariableFunctionNode(node) ||
(node.type === 'word' && node.value.includes(`___CSS_LOADER_IMPORT___`))
) {
abort = true;
return false;
}
});
return abort;
}
/**
* @param {import('postcss').Declaration} decl
* @return {string}
*/
function getValue(decl) {
let { value, raws } = decl;
if (raws && raws.value && raws.value.raw) {
value = raws.value.raw;
}
return value;
}
/**
* @type {import('postcss').PluginCreator<void>}
* @return {import('postcss').Plugin}
*/
function pluginCreator() {
return {
postcssPlugin: 'postcss-ordered-values',
prepare() {
const cache = new Map();
return {
OnceExit(css) {
css.walkDecls((decl) => {
const lowerCasedProp = decl.prop.toLowerCase();
const normalizedProp = vendorUnprefixed(lowerCasedProp);
const processor = rules.get(normalizedProp);
if (!processor) {
return;
}
const value = getValue(decl);
if (cache.has(value)) {
decl.value = cache.get(value);
return;
}
const parsed = valueParser(value);
if (parsed.nodes.length < 2 || shouldAbort(parsed)) {
cache.set(value, value);
return;
}
const result = processor(parsed);
decl.value = result.toString();
cache.set(value, result.toString());
});
},
};
},
};
}
pluginCreator.postcss = true;
module.exports = pluginCreator;
+8
View File
@@ -0,0 +1,8 @@
'use strict';
/** @return {import('postcss-value-parser').SpaceNode} */
module.exports = function addSpace() {
return /** @type import('postcss-value-parser').SpaceNode */ ({
type: 'space',
value: ' ',
});
};
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const { stringify } = require('postcss-value-parser');
/**
* @param {import('postcss-value-parser').Node[][]} values
* @return {string}
*/
module.exports = function getValue(values) {
return stringify(flatten(values));
};
/**
* @param {import('postcss-value-parser').Node[][]} values
* @return {import('postcss-value-parser').Node[]}
*/
function flatten(values) {
/** @type {import('postcss-value-parser').Node[]} */
const nodes = [];
for (const [index, arg] of values.entries()) {
arg.forEach((val, idx) => {
if (
idx === arg.length - 1 &&
index === values.length - 1 &&
val.type === 'space'
) {
return;
}
nodes.push(val);
});
if (index !== values.length - 1) {
nodes[nodes.length - 1].type = 'div';
nodes[nodes.length - 1].value = ',';
}
}
return nodes;
}
+8
View File
@@ -0,0 +1,8 @@
'use strict';
/**
* @param {string[]} grid
* @return {string}
*/
module.exports = function joinGridVal(grid) {
return grid.join(' / ').trim();
};
+3
View File
@@ -0,0 +1,3 @@
'use strict';
// All of the curently implemented math functions
module.exports = new Set(['calc', 'clamp', 'max', 'min']);
+10
View File
@@ -0,0 +1,10 @@
'use strict';
/**
* @param {string} prop
* @return {string}
*/
function vendorUnprefixed(prop) {
return prop.replace(/^-\w+-/, '');
}
module.exports = vendorUnprefixed;
+148
View File
@@ -0,0 +1,148 @@
'use strict';
const { unit } = require('postcss-value-parser');
const { getArguments } = require('cssnano-utils');
const addSpace = require('../lib/addSpace');
const getValue = require('../lib/getValue');
// animation: [ none | <keyframes-name> ] || <time> || <single-timing-function> || <time> || <single-animation-iteration-count> || <single-animation-direction> || <single-animation-fill-mode> || <single-animation-play-state>
const functions = new Set(['steps', 'cubic-bezier', 'frames']);
const keywords = new Set([
'ease',
'ease-in',
'ease-in-out',
'ease-out',
'linear',
'step-end',
'step-start',
]);
const directions = new Set([
'normal',
'reverse',
'alternate',
'alternate-reverse',
]);
const fillModes = new Set(['none', 'forwards', 'backwards', 'both']);
const playStates = new Set(['running', 'paused']);
const timeUnits = new Set(['ms', 's']);
/**
* @param {string} value
* @param {string} type
* @return {boolean}
*/
const isTimingFunction = (value, type) => {
return (type === 'function' && functions.has(value)) || keywords.has(value);
};
/**
* @param {string} value
* @return {boolean}
*/
const isDirection = (value) => {
return directions.has(value);
};
/**
* @param {string} value
* @return {boolean}
*/
const isFillMode = (value) => {
return fillModes.has(value);
};
/**
* @param {string} value
* @return {boolean}
*/
const isPlayState = (value) => {
return playStates.has(value);
};
/**
* @param {string} value
* @return {boolean}
*/
const isTime = (value) => {
const quantity = unit(value);
return quantity && timeUnits.has(quantity.unit);
};
/**
* @param {string} value
* @return {boolean}
*/
const isIterationCount = (value) => {
const quantity = unit(value);
return value === 'infinite' || (quantity && !quantity.unit);
};
const stateConditions = [
{ property: 'duration', delegate: isTime },
{ property: 'timingFunction', delegate: isTimingFunction },
{ property: 'delay', delegate: isTime },
{ property: 'iterationCount', delegate: isIterationCount },
{ property: 'direction', delegate: isDirection },
{ property: 'fillMode', delegate: isFillMode },
{ property: 'playState', delegate: isPlayState },
];
/**
* @param {import('postcss-value-parser').Node[][]} args
* @return {import('postcss-value-parser').Node[][]}
*/
function normalize(args) {
const list = [];
for (const arg of args) {
/** @type {Record<string, import('postcss-value-parser').Node[]>} */
const state = {
name: [],
duration: [],
timingFunction: [],
delay: [],
iterationCount: [],
direction: [],
fillMode: [],
playState: [],
};
arg.forEach((node) => {
let { type, value } = node;
if (type === 'space') {
return;
}
value = value.toLowerCase();
const hasMatch = stateConditions.some(({ property, delegate }) => {
if (delegate(value, type) && !state[property].length) {
state[property] = [node, addSpace()];
return true;
}
});
if (!hasMatch) {
state.name = [...state.name, node, addSpace()];
}
});
list.push([
...state.name,
...state.duration,
...state.timingFunction,
...state.delay,
...state.iterationCount,
...state.direction,
...state.fillMode,
...state.playState,
]);
}
return list;
}
/**
* @param {import('postcss-value-parser').ParsedValue} parsed
* @return {string}
*/
module.exports = function normalizeAnimation(parsed) {
const values = normalize(getArguments(parsed));
return getValue(values);
};
+60
View File
@@ -0,0 +1,60 @@
'use strict';
const { unit, stringify } = require('postcss-value-parser');
const mathFunctions = require('../lib/mathfunctions.js');
// border: <line-width> || <line-style> || <color>
// outline: <outline-color> || <outline-style> || <outline-width>
const borderWidths = new Set(['thin', 'medium', 'thick']);
const borderStyles = new Set([
'none',
'auto', // only in outline-style
'hidden',
'dotted',
'dashed',
'solid',
'double',
'groove',
'ridge',
'inset',
'outset',
]);
/**
* @param {import('postcss-value-parser').ParsedValue} border
* @return {string}
*/
module.exports = function normalizeBorder(border) {
const order = { width: '', style: '', color: '' };
border.walk((node) => {
const { type, value } = node;
if (type === 'word') {
if (borderStyles.has(value.toLowerCase())) {
order.style = value;
return false;
}
if (borderWidths.has(value.toLowerCase()) || unit(value.toLowerCase())) {
if (order.width !== '') {
order.width = `${order.width} ${value}`;
return false;
}
order.width = value;
return false;
}
order.color = value;
return false;
}
if (type === 'function') {
if (mathFunctions.has(value.toLowerCase())) {
order.width = stringify(node);
} else {
order.color = stringify(node);
}
return false;
}
});
return `${order.width} ${order.style} ${order.color}`.trim();
};
+73
View File
@@ -0,0 +1,73 @@
'use strict';
const { unit } = require('postcss-value-parser');
const { getArguments } = require('cssnano-utils');
const addSpace = require('../lib/addSpace');
const getValue = require('../lib/getValue');
const mathFunctions = require('../lib/mathfunctions.js');
const vendorUnprefixed = require('../lib/vendorUnprefixed.js');
// box-shadow: inset? && <length>{2,4} && <color>?
/**
* @param {import('postcss-value-parser').ParsedValue} parsed
* @return {string}
*/
module.exports = function normalizeBoxShadow(parsed) {
let args = getArguments(parsed);
const normalized = normalize(args);
if (normalized === false) {
return parsed.toString();
}
return getValue(normalized);
};
/**
* @param {import('postcss-value-parser').Node[][]} args
* @return {false | import('postcss-value-parser').Node[][]}
*/
function normalize(args) {
const list = [];
let abort = false;
for (const arg of args) {
/** @type {import('postcss-value-parser').Node[]} */
let val = [];
/** @type {Record<'inset'|'color', import('postcss-value-parser').Node[]>} */
let state = {
inset: [],
color: [],
};
arg.forEach((node) => {
const { type, value } = node;
if (
type === 'function' &&
mathFunctions.has(vendorUnprefixed(value.toLowerCase()))
) {
abort = true;
return;
}
if (type === 'space') {
return;
}
if (unit(value)) {
val = [...val, node, addSpace()];
} else if (value.toLowerCase() === 'inset') {
state.inset = [...state.inset, node, addSpace()];
} else {
state.color = [...state.color, node, addSpace()];
}
});
if (abort) {
return false;
}
list.push([...state.inset, ...val, ...state.color]);
}
return list;
}
+39
View File
@@ -0,0 +1,39 @@
'use strict';
const { unit } = require('postcss-value-parser');
/**
* @param {string} value
* @return {boolean}
*/
function hasUnit(value) {
const parsedVal = unit(value);
return parsedVal && parsedVal.unit !== '';
}
/**
* @param {import('postcss-value-parser').ParsedValue} columns
* @return {import('postcss-value-parser').ParsedValue | string}
*/
module.exports = (columns) => {
/** @type {string[]} */
const widths = [];
/** @type {string[]} */
const other = [];
columns.walk((node) => {
const { type, value } = node;
if (type === 'word') {
if (hasUnit(value)) {
widths.push(value);
} else {
other.push(value);
}
}
});
// only transform if declaration is not invalid or a single value
if (other.length === 1 && widths.length === 1) {
return `${widths[0].trimStart()} ${other[0].trimStart()}`;
}
return columns;
};
+36
View File
@@ -0,0 +1,36 @@
'use strict';
// flex-flow: <flex-direction> || <flex-wrap>
const flexDirection = new Set([
'row',
'row-reverse',
'column',
'column-reverse',
]);
const flexWrap = new Set(['nowrap', 'wrap', 'wrap-reverse']);
/**
* @param {import('postcss-value-parser').ParsedValue} flexFlow
* @return {string}
*/
module.exports = function normalizeFlexFlow(flexFlow) {
let order = {
direction: '',
wrap: '',
};
flexFlow.walk(({ value }) => {
if (flexDirection.has(value.toLowerCase())) {
order.direction = value;
return;
}
if (flexWrap.has(value.toLowerCase())) {
order.wrap = value;
return;
}
});
return `${order.direction} ${order.wrap}`.trim();
};
+100
View File
@@ -0,0 +1,100 @@
'use strict';
const joinGridValue = require('../lib/joinGridValue');
/**
* @param {import('postcss-value-parser').ParsedValue} gridAutoFlow
* @return {import('postcss-value-parser').ParsedValue | string}
*/
const normalizeGridAutoFlow = (gridAutoFlow) => {
let newValue = { front: '', back: '' };
let shouldNormalize = false;
gridAutoFlow.walk((node) => {
if (node.value === 'dense') {
shouldNormalize = true;
newValue.back = node.value;
} else if (['row', 'column'].includes(node.value.trim().toLowerCase())) {
shouldNormalize = true;
newValue.front = node.value;
} else {
shouldNormalize = false;
}
});
if (shouldNormalize) {
return `${newValue.front.trim()} ${newValue.back.trim()}`;
}
return gridAutoFlow;
};
/**
* @param {import('postcss-value-parser').ParsedValue} gridGap
* @return {import('postcss-value-parser').ParsedValue | string}
*/
const normalizeGridColumnRowGap = (gridGap) => {
let newValue = { front: '', back: '' };
let shouldNormalize = false;
gridGap.walk((node) => {
// console.log(node);
if (node.value === 'normal') {
shouldNormalize = true;
newValue.front = node.value;
} else {
newValue.back = `${newValue.back} ${node.value}`;
}
});
if (shouldNormalize) {
return `${newValue.front.trim()} ${newValue.back.trim()}`;
}
return gridGap;
};
/**
* @param {import('postcss-value-parser').ParsedValue} grid
* @return {string | string[]}
*/
const normalizeGridColumnRow = (grid) => {
// cant do normalization here using node, so copy it as a string
let gridValue = grid.toString().split('/'); // node -> string value, split -> " 2 / 3 span " -> [' 2','3 span ']
if (gridValue.length > 1) {
return joinGridValue(
gridValue.map((gridLine) => {
let normalizeValue = {
front: '',
back: '',
};
gridLine = gridLine.trim(); // '3 span ' -> '3 span'
gridLine.split(' ').forEach((node) => {
// ['3','span']
if (node === 'span') {
normalizeValue.front = node; // span _
} else {
normalizeValue.back = `${normalizeValue.back} ${node}`; // _ 3
}
});
return `${normalizeValue.front.trim()} ${normalizeValue.back.trim()}`; // span 3
})
// returns "2 / span 3"
);
}
// doing this separating if `/` is not present as while joining('/') , it will add `/` at the end
return gridValue.map((gridLine) => {
let normalizeValue = {
front: '',
back: '',
};
gridLine = gridLine.trim();
gridLine.split(' ').forEach((node) => {
if (node === 'span') {
normalizeValue.front = node;
} else {
normalizeValue.back = `${normalizeValue.back} ${node}`;
}
});
return `${normalizeValue.front.trim()} ${normalizeValue.back.trim()}`;
});
};
module.exports = {
normalizeGridAutoFlow,
normalizeGridColumnRowGap,
normalizeGridColumnRow,
};
+44
View File
@@ -0,0 +1,44 @@
'use strict';
const valueParser = require('postcss-value-parser');
const listStyleTypes = require('./listStyleTypes.json');
const definedTypes = new Set(listStyleTypes['list-style-type']);
const definedPosition = new Set(['inside', 'outside']);
/**
* @param {import('postcss-value-parser').ParsedValue} listStyle
* @return {string}
*/
module.exports = function listStyleNormalizer(listStyle) {
const order = { type: '', position: '', image: '' };
listStyle.walk((decl) => {
if (decl.type === 'word') {
if (definedTypes.has(decl.value)) {
// its a type field
order.type = `${order.type} ${decl.value}`;
} else if (definedPosition.has(decl.value)) {
order.position = `${order.position} ${decl.value}`;
} else if (decl.value === 'none') {
if (
order.type
.split(' ')
.filter((e) => e !== '' && e !== ' ')
.includes('none')
) {
order.image = `${order.image} ${decl.value}`;
} else {
order.type = `${order.type} ${decl.value}`;
}
} else {
order.type = `${order.type} ${decl.value}`;
}
}
if (decl.type === 'function') {
order.image = `${order.image} ${valueParser.stringify(decl)}`;
}
});
return `${order.type.trim()} ${order.position.trim()} ${order.image.trim()}`.trim();
};
+102
View File
@@ -0,0 +1,102 @@
{
"list-style-type": [
"afar",
"amharic",
"amharic-abegede",
"arabic-indic",
"armenian",
"asterisks",
"bengali",
"binary",
"cambodian",
"circle",
"cjk-decimal",
"cjk-earthly-branch",
"cjk-heavenly-stem",
"cjk-ideographic",
"decimal",
"decimal-leading-zero",
"devanagari",
"disc",
"disclosure-closed",
"disclosure-open",
"ethiopic",
"ethiopic-abegede",
"ethiopic-abegede-am-et",
"ethiopic-abegede-gez",
"ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et",
"ethiopic-halehame",
"ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et",
"ethiopic-halehame-am",
"ethiopic-halehame-am-et",
"ethiopic-halehame-gez",
"ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et",
"ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er",
"ethiopic-halehame-ti-et",
"ethiopic-halehame-tig",
"ethiopic-numeric",
"footnotes",
"georgian",
"gujarati",
"gurmukhi",
"hangul",
"hangul-consonant",
"hebrew",
"hiragana",
"hiragana-iroha",
"japanese-formal",
"japanese-informal",
"kannada",
"katakana",
"katakana-iroha",
"khmer",
"korean-hangul-formal",
"korean-hanja-formal",
"korean-hanja-informal",
"lao",
"lower-alpha",
"lower-armenian",
"lower-greek",
"lower-hexadecimal",
"lower-latin",
"lower-norwegian",
"lower-roman",
"malayalam",
"mongolian",
"myanmar",
"octal",
"oriya",
"oromo",
"persian",
"sidama",
"simp-chinese-formal",
"simp-chinese-informal",
"somali",
"square",
"string",
"symbols",
"tamil",
"telugu",
"thai",
"tibetan",
"tigre",
"tigrinya-er",
"tigrinya-er-abegede",
"tigrinya-et",
"tigrinya-et-abegede",
"trad-chinese-formal",
"trad-chinese-informal",
"upper-alpha",
"upper-armenian",
"upper-greek",
"upper-hexadecimal",
"upper-latin",
"upper-norwegian",
"upper-roman",
"urdu"
]
}
+76
View File
@@ -0,0 +1,76 @@
'use strict';
const { unit } = require('postcss-value-parser');
const { getArguments } = require('cssnano-utils');
const addSpace = require('../lib/addSpace');
const getValue = require('../lib/getValue');
// transition: [ none | <single-transition-property> ] || <time> || <single-transition-timing-function> || <time>
const timingFunctions = new Set([
'ease',
'linear',
'ease-in',
'ease-out',
'ease-in-out',
'step-start',
'step-end',
]);
/**
* @param {import('postcss-value-parser').Node[][]} args
* @return {import('postcss-value-parser').Node[][]}
*/
function normalize(args) {
const list = [];
for (const arg of args) {
/** @type {Record<string, import('postcss-value-parser').Node[]>} */
let state = {
timingFunction: [],
property: [],
time1: [],
time2: [],
};
arg.forEach((node) => {
const { type, value } = node;
if (type === 'space') {
return;
}
if (
type === 'function' &&
new Set(['steps', 'cubic-bezier']).has(value.toLowerCase())
) {
state.timingFunction = [...state.timingFunction, node, addSpace()];
} else if (unit(value)) {
if (!state.time1.length) {
state.time1 = [...state.time1, node, addSpace()];
} else {
state.time2 = [...state.time2, node, addSpace()];
}
} else if (timingFunctions.has(value.toLowerCase())) {
state.timingFunction = [...state.timingFunction, node, addSpace()];
} else {
state.property = [...state.property, node, addSpace()];
}
});
list.push([
...state.property,
...state.time1,
...state.timingFunction,
...state.time2,
]);
}
return list;
}
/**
* @param {import('postcss-value-parser').ParsedValue} parsed
* @return {string}
*/
module.exports = function normalizeTransition(parsed) {
const values = normalize(getArguments(parsed));
return getValue(values);
};
+9
View File
@@ -0,0 +1,9 @@
export = pluginCreator;
/**
* @type {import('postcss').PluginCreator<void>}
* @return {import('postcss').Plugin}
*/
declare function pluginCreator(): import('postcss').Plugin;
declare namespace pluginCreator {
const postcss: true;
}
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(): import('postcss-value-parser').SpaceNode;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(values: import('postcss-value-parser').Node[][]): string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(grid: string[]): string;
export = _exports;
+14
View File
@@ -0,0 +1,14 @@
declare const _exports: {
add(value: string): Set<string>;
clear(): void;
delete(value: string): boolean;
forEach(callbackfn: (value: string, value2: string, set: Set<string>) => void, thisArg?: any): void;
has(value: string): boolean;
readonly size: number;
entries(): IterableIterator<[string, string]>;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<string>;
readonly [Symbol.toStringTag]: string;
};
export = _exports;
+6
View File
@@ -0,0 +1,6 @@
export = vendorUnprefixed;
/**
* @param {string} prop
* @return {string}
*/
declare function vendorUnprefixed(prop: string): string;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(parsed: import('postcss-value-parser').ParsedValue): string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(border: import('postcss-value-parser').ParsedValue): string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(parsed: import('postcss-value-parser').ParsedValue): string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(columns: import('postcss-value-parser').ParsedValue): import('postcss-value-parser').ParsedValue | string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(flexFlow: import('postcss-value-parser').ParsedValue): string;
export = _exports;
+15
View File
@@ -0,0 +1,15 @@
/**
* @param {import('postcss-value-parser').ParsedValue} gridAutoFlow
* @return {import('postcss-value-parser').ParsedValue | string}
*/
export function normalizeGridAutoFlow(gridAutoFlow: import('postcss-value-parser').ParsedValue): import('postcss-value-parser').ParsedValue | string;
/**
* @param {import('postcss-value-parser').ParsedValue} gridGap
* @return {import('postcss-value-parser').ParsedValue | string}
*/
export function normalizeGridColumnRowGap(gridGap: import('postcss-value-parser').ParsedValue): import('postcss-value-parser').ParsedValue | string;
/**
* @param {import('postcss-value-parser').ParsedValue} grid
* @return {string | string[]}
*/
export function normalizeGridColumnRow(grid: import('postcss-value-parser').ParsedValue): string | string[];
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(listStyle: import('postcss-value-parser').ParsedValue): string;
export = _exports;
+2
View File
@@ -0,0 +1,2 @@
declare function _exports(parsed: import('postcss-value-parser').ParsedValue): string;
export = _exports;