postcss-convert-values 5.0.2 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,17 +1,14 @@
1
1
  {
2
2
  "name": "postcss-convert-values",
3
- "version": "5.0.2",
3
+ "version": "5.1.0",
4
4
  "description": "Convert values with PostCSS (e.g. ms -> s)",
5
- "main": "dist/index.js",
5
+ "main": "src/index.js",
6
+ "types": "types/index.d.ts",
6
7
  "files": [
7
8
  "LICENSE-MIT",
8
- "dist"
9
+ "src",
10
+ "types"
9
11
  ],
10
- "scripts": {
11
- "prebuild": "rimraf dist",
12
- "build": "cross-env BABEL_ENV=publish babel src --config-file ../../babel.config.json --out-dir dist --ignore \"**/__tests__/\"",
13
- "prepare": "yarn build"
14
- },
15
12
  "keywords": [
16
13
  "css",
17
14
  "optimisation",
@@ -27,7 +24,7 @@
27
24
  },
28
25
  "repository": "cssnano/cssnano",
29
26
  "dependencies": {
30
- "postcss-value-parser": "^4.1.0"
27
+ "postcss-value-parser": "^4.2.0"
31
28
  },
32
29
  "bugs": {
33
30
  "url": "https://github.com/cssnano/cssnano/issues"
@@ -41,5 +38,5 @@
41
38
  "peerDependencies": {
42
39
  "postcss": "^8.2.15"
43
40
  },
44
- "gitHead": "2d84646671c7075f8dae35de310351aac3436bc0"
45
- }
41
+ "readme": "# [postcss][postcss]-convert-values\n\n> Convert values with PostCSS (e.g. ms -> s)\n\n## Install\n\nWith [npm](https://npmjs.org/package/postcss-convert-values) do:\n\n```\nnpm install postcss-convert-values --save\n```\n\n## Example\n\nThis plugin reduces CSS size by converting values to use different units\nwhere possible; for example, `500ms` can be represented as `.5s`. You can\nread more about these units in [this article][csstricks].\n\n### Input\n\n```css\nh1 {\n font-size: 16px;\n width: 0em\n}\n```\n\n### Output\n\n```css\nh1 {\n font-size: 1pc;\n width: 0\n}\n```\n\nNote that this plugin only covers conversions for duration and absolute length\nvalues. For color conversions, use [postcss-colormin][colormin].\n\n## API\n\n### convertValues([options])\n\n#### options\n\n##### length\n\nType: `boolean`\nDefault: `true`\n\nPass `false` to disable conversion from `px` to other absolute length units,\nsuch as `pc` & `pt` & vice versa.\n\n##### time\n\nType: `boolean`\nDefault: `true`\n\nPass `false` to disable conversion from `ms` to `s` & vice versa.\n\n##### angle\n\nType: `boolean`\nDefault: `true`\n\nPass `false` to disable conversion from `deg` to `turn` & vice versa.\n\n##### precision\n\nType: `boolean|number`\nDefault: `false`\n\nSpecify any numeric value here to round `px` values to that many decimal places;\nfor example, using `{precision: 2}` will round `6.66667px` to `6.67px`, and\n`{precision: 0}` will round it to `7px`. Passing `false` (the default) will\nleave these values as is.\n\nIt is recommended for most use cases to set this option to `2`.\n\n\n## Usage\n\nSee the [PostCSS documentation](https://github.com/postcss/postcss#usage) for\nexamples for your environment.\n\n\n## Contributors\n\nSee [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md).\n\n\n## License\n\nMIT © [Ben Briggs](http://beneb.info)\n\n\n[postcss]: https://github.com/postcss/postcss\n[csstricks]: https://css-tricks.com/the-lengths-of-css/\n"
42
+ }
package/src/index.js ADDED
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+ const valueParser = require('postcss-value-parser');
3
+ const convert = require('./lib/convert.js');
4
+
5
+ const LENGTH_UNITS = new Set([
6
+ 'em',
7
+ 'ex',
8
+ 'ch',
9
+ 'rem',
10
+ 'vw',
11
+ 'vh',
12
+ 'vmin',
13
+ 'vmax',
14
+ 'cm',
15
+ 'mm',
16
+ 'q',
17
+ 'in',
18
+ 'pt',
19
+ 'pc',
20
+ 'px',
21
+ ]);
22
+
23
+ // These properties only accept percentages, so no point in trying to transform
24
+ const notALength = new Set([
25
+ 'descent-override',
26
+ 'ascent-override',
27
+ 'font-stretch',
28
+ 'size-adjust',
29
+ 'line-gap-override',
30
+ ]);
31
+
32
+ // Can't change the unit on these properties when they're 0
33
+ const keepWhenZero = new Set([
34
+ 'stroke-dashoffset',
35
+ 'stroke-width',
36
+ 'line-height',
37
+ ]);
38
+
39
+ /**
40
+ * Numbers without digits after the dot are technically invalid,
41
+ * but in that case css-value-parser returns the dot as part of the unit,
42
+ * so we use this to remove the dot.
43
+ *
44
+ * @param {string} item
45
+ * @return {string}
46
+ */
47
+ function stripLeadingDot(item) {
48
+ if (item.charCodeAt(0) === '.'.charCodeAt(0)) {
49
+ return item.slice(1);
50
+ } else {
51
+ return item;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * @param {valueParser.Node} node
57
+ * @param {Options} opts
58
+ * @param {boolean} keepZeroUnit
59
+ * @return {void}
60
+ */
61
+ function parseWord(node, opts, keepZeroUnit) {
62
+ const pair = valueParser.unit(node.value);
63
+ if (pair) {
64
+ const num = Number(pair.number);
65
+ const u = stripLeadingDot(pair.unit);
66
+ if (num === 0) {
67
+ node.value =
68
+ 0 +
69
+ (keepZeroUnit || (!LENGTH_UNITS.has(u.toLowerCase()) && u !== '%')
70
+ ? u
71
+ : '');
72
+ } else {
73
+ node.value = convert(num, u, opts);
74
+
75
+ if (
76
+ typeof opts.precision === 'number' &&
77
+ u.toLowerCase() === 'px' &&
78
+ pair.number.includes('.')
79
+ ) {
80
+ const precision = Math.pow(10, opts.precision);
81
+ node.value =
82
+ Math.round(parseFloat(node.value) * precision) / precision + u;
83
+ }
84
+ }
85
+ }
86
+ }
87
+
88
+ /**
89
+ * @param {valueParser.WordNode} node
90
+ * @return {void}
91
+ */
92
+ function clampOpacity(node) {
93
+ const pair = valueParser.unit(node.value);
94
+ if (!pair) {
95
+ return;
96
+ }
97
+ let num = Number(pair.number);
98
+ if (num > 1) {
99
+ node.value = pair.unit === '%' ? num + pair.unit : 1 + pair.unit;
100
+ } else if (num < 0) {
101
+ node.value = 0 + pair.unit;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * @param {import('postcss').Declaration} decl
107
+ * @return {boolean}
108
+ */
109
+ function shouldKeepZeroUnit(decl) {
110
+ const { parent } = decl;
111
+ const lowerCasedProp = decl.prop.toLowerCase();
112
+ return (
113
+ (decl.value.includes('%') &&
114
+ (lowerCasedProp === 'max-height' || lowerCasedProp === 'height')) ||
115
+ (parent &&
116
+ parent.parent &&
117
+ parent.parent.type === 'atrule' &&
118
+ /** @type {import('postcss').AtRule} */ (
119
+ parent.parent
120
+ ).name.toLowerCase() === 'keyframes' &&
121
+ lowerCasedProp === 'stroke-dasharray') ||
122
+ keepWhenZero.has(lowerCasedProp)
123
+ );
124
+ }
125
+ /**
126
+ * @param {Options} opts
127
+ * @param {import('postcss').Declaration} decl
128
+ * @return {void}
129
+ */
130
+ function transform(opts, decl) {
131
+ const lowerCasedProp = decl.prop.toLowerCase();
132
+ if (
133
+ lowerCasedProp.includes('flex') ||
134
+ lowerCasedProp.indexOf('--') === 0 ||
135
+ notALength.has(lowerCasedProp)
136
+ ) {
137
+ return;
138
+ }
139
+
140
+ decl.value = valueParser(decl.value)
141
+ .walk((node) => {
142
+ const lowerCasedValue = node.value.toLowerCase();
143
+
144
+ if (node.type === 'word') {
145
+ parseWord(node, opts, shouldKeepZeroUnit(decl));
146
+ if (
147
+ lowerCasedProp === 'opacity' ||
148
+ lowerCasedProp === 'shape-image-threshold'
149
+ ) {
150
+ clampOpacity(node);
151
+ }
152
+ } else if (node.type === 'function') {
153
+ if (
154
+ lowerCasedValue === 'calc' ||
155
+ lowerCasedValue === 'min' ||
156
+ lowerCasedValue === 'max' ||
157
+ lowerCasedValue === 'clamp' ||
158
+ lowerCasedValue === 'hsl' ||
159
+ lowerCasedValue === 'hsla'
160
+ ) {
161
+ valueParser.walk(node.nodes, (n) => {
162
+ if (n.type === 'word') {
163
+ parseWord(n, opts, true);
164
+ }
165
+ });
166
+ return false;
167
+ }
168
+ if (lowerCasedValue === 'url') {
169
+ return false;
170
+ }
171
+ }
172
+ })
173
+ .toString();
174
+ }
175
+
176
+ const plugin = 'postcss-convert-values';
177
+ /**
178
+ * @typedef {{precision: boolean | number, angle?: boolean, time?: boolean, length?: boolean}} Options */
179
+ /**
180
+ * @type {import('postcss').PluginCreator<Options>}
181
+ * @param {Options} opts
182
+ * @return {import('postcss').Plugin}
183
+ */
184
+ function pluginCreator(opts = { precision: false }) {
185
+ return {
186
+ postcssPlugin: plugin,
187
+ OnceExit(css) {
188
+ css.walkDecls(transform.bind(null, opts));
189
+ },
190
+ };
191
+ }
192
+
193
+ pluginCreator.postcss = true;
194
+ module.exports = pluginCreator;
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+ const lengthConv = new Map([
3
+ ['in', 96],
4
+ ['px', 1],
5
+ ['pt', 4 / 3],
6
+ ['pc', 16],
7
+ ]);
8
+
9
+ const timeConv = new Map([
10
+ ['s', 1000],
11
+ ['ms', 1],
12
+ ]);
13
+
14
+ const angleConv = new Map([
15
+ ['turn', 360],
16
+ ['deg', 1],
17
+ ]);
18
+ /**
19
+ * @param {number} number
20
+ * @return {string}
21
+ */
22
+ function dropLeadingZero(number) {
23
+ const value = String(number);
24
+
25
+ if (number % 1) {
26
+ if (value[0] === '0') {
27
+ return value.slice(1);
28
+ }
29
+
30
+ if (value[0] === '-' && value[1] === '0') {
31
+ return '-' + value.slice(2);
32
+ }
33
+ }
34
+
35
+ return value;
36
+ }
37
+ /**
38
+ * @param {number} number
39
+ * @param {string} originalUnit
40
+ * @param {Map<string, number>} conversions
41
+ * @return {string}
42
+ */
43
+ function transform(number, originalUnit, conversions) {
44
+ let conversionUnits = [...conversions.keys()].filter((u) => {
45
+ return originalUnit !== u;
46
+ });
47
+
48
+ const base = number * /** @type {number} */ (conversions.get(originalUnit));
49
+
50
+ return conversionUnits
51
+ .map(
52
+ (u) =>
53
+ dropLeadingZero(base / /** @type {number} */ (conversions.get(u))) + u
54
+ )
55
+ .reduce((a, b) => (a.length < b.length ? a : b));
56
+ }
57
+
58
+ /**
59
+ * @param {number} number
60
+ * @param {string} unit
61
+ * @param {{time?: boolean, length?: boolean, angle?: boolean}} options
62
+ * @return {string}
63
+ */
64
+ module.exports = function (number, unit, { time, length, angle }) {
65
+ let value = dropLeadingZero(number) + (unit ? unit : '');
66
+ let converted;
67
+ const lowerCaseUnit = unit.toLowerCase();
68
+ if (length !== false && lengthConv.has(lowerCaseUnit)) {
69
+ converted = transform(number, lowerCaseUnit, lengthConv);
70
+ }
71
+
72
+ if (time !== false && timeConv.has(lowerCaseUnit)) {
73
+ converted = transform(number, lowerCaseUnit, timeConv);
74
+ }
75
+
76
+ if (angle !== false && angleConv.has(lowerCaseUnit)) {
77
+ converted = transform(number, lowerCaseUnit, angleConv);
78
+ }
79
+
80
+ if (converted && converted.length < value.length) {
81
+ value = converted;
82
+ }
83
+
84
+ return value;
85
+ };
@@ -0,0 +1,19 @@
1
+ export = pluginCreator;
2
+ /**
3
+ * @typedef {{precision: boolean | number, angle?: boolean, time?: boolean, length?: boolean}} Options */
4
+ /**
5
+ * @type {import('postcss').PluginCreator<Options>}
6
+ * @param {Options} opts
7
+ * @return {import('postcss').Plugin}
8
+ */
9
+ declare function pluginCreator(opts?: Options): import('postcss').Plugin;
10
+ declare namespace pluginCreator {
11
+ export { postcss, Options };
12
+ }
13
+ type Options = {
14
+ precision: boolean | number;
15
+ angle?: boolean;
16
+ time?: boolean;
17
+ length?: boolean;
18
+ };
19
+ declare var postcss: true;
@@ -0,0 +1,6 @@
1
+ declare function _exports(number: number, unit: string, { time, length, angle }: {
2
+ time?: boolean;
3
+ length?: boolean;
4
+ angle?: boolean;
5
+ }): string;
6
+ export = _exports;
package/dist/index.js DELETED
@@ -1,132 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- var _postcssValueParser = _interopRequireWildcard(require("postcss-value-parser"));
9
-
10
- var _convert = _interopRequireDefault(require("./lib/convert"));
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
-
16
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
-
18
- const LENGTH_UNITS = ['em', 'ex', 'ch', 'rem', 'vw', 'vh', 'vmin', 'vmax', 'cm', 'mm', 'q', 'in', 'pt', 'pc', 'px']; // These properties only accept percentages, so no point in trying to transform
19
-
20
- const notALength = new Set(['descent-override', 'ascent-override', 'font-stretch', 'size-adjust', 'line-gap-override']); // Can't change the unit on these properties when they're 0
21
-
22
- const keepWhenZero = new Set(['stroke-dashoffset', 'stroke-width', 'line-height']);
23
- /*
24
- * Numbers without digits after the dot are technically invalid,
25
- * but in that case css-value-parser returns the dot as part of the unit,
26
- * so we use this to remove the dot.
27
- */
28
-
29
- function stripLeadingDot(item) {
30
- if (item.charCodeAt(0) === '.'.charCodeAt(0)) {
31
- return item.slice(1);
32
- } else {
33
- return item;
34
- }
35
- }
36
-
37
- function parseWord(node, opts, keepZeroUnit) {
38
- const pair = (0, _postcssValueParser.unit)(node.value);
39
-
40
- if (pair) {
41
- const num = Number(pair.number);
42
- const u = stripLeadingDot(pair.unit);
43
-
44
- if (num === 0) {
45
- node.value = 0 + (keepZeroUnit || !~LENGTH_UNITS.indexOf(u.toLowerCase()) && u !== '%' ? u : '');
46
- } else {
47
- node.value = (0, _convert.default)(num, u, opts);
48
-
49
- if (typeof opts.precision === 'number' && u.toLowerCase() === 'px' && ~pair.number.indexOf('.')) {
50
- const precision = Math.pow(10, opts.precision);
51
- node.value = Math.round(parseFloat(node.value) * precision) / precision + u;
52
- }
53
- }
54
- }
55
- }
56
-
57
- function clampOpacity(node) {
58
- const pair = (0, _postcssValueParser.unit)(node.value);
59
-
60
- if (!pair) {
61
- return;
62
- }
63
-
64
- let num = Number(pair.number);
65
-
66
- if (num > 1) {
67
- node.value = pair.unit === '%' ? num + pair.unit : 1 + pair.unit;
68
- } else if (num < 0) {
69
- node.value = 0 + pair.unit;
70
- }
71
- }
72
-
73
- function shouldKeepZeroUnit(decl) {
74
- const {
75
- parent
76
- } = decl;
77
- const lowerCasedProp = decl.prop.toLowerCase();
78
- return ~decl.value.indexOf('%') && (lowerCasedProp === 'max-height' || lowerCasedProp === 'height') || parent.parent && parent.parent.name && parent.parent.name.toLowerCase() === 'keyframes' && lowerCasedProp === 'stroke-dasharray' || keepWhenZero.has(lowerCasedProp);
79
- }
80
-
81
- function transform(opts, decl) {
82
- const lowerCasedProp = decl.prop.toLowerCase();
83
-
84
- if (~lowerCasedProp.indexOf('flex') || lowerCasedProp.indexOf('--') === 0 || notALength.has(lowerCasedProp)) {
85
- return;
86
- }
87
-
88
- decl.value = (0, _postcssValueParser.default)(decl.value).walk(node => {
89
- const lowerCasedValue = node.value.toLowerCase();
90
-
91
- if (node.type === 'word') {
92
- parseWord(node, opts, shouldKeepZeroUnit(decl));
93
-
94
- if (lowerCasedProp === 'opacity' || lowerCasedProp === 'shape-image-threshold') {
95
- clampOpacity(node);
96
- }
97
- } else if (node.type === 'function') {
98
- if (lowerCasedValue === 'calc' || lowerCasedValue === 'min' || lowerCasedValue === 'max' || lowerCasedValue === 'clamp' || lowerCasedValue === 'hsl' || lowerCasedValue === 'hsla') {
99
- (0, _postcssValueParser.walk)(node.nodes, n => {
100
- if (n.type === 'word') {
101
- parseWord(n, opts, true);
102
- }
103
- });
104
- return false;
105
- }
106
-
107
- if (lowerCasedValue === 'url') {
108
- return false;
109
- }
110
- }
111
- }).toString();
112
- }
113
-
114
- const plugin = 'postcss-convert-values';
115
-
116
- function pluginCreator(opts = {
117
- precision: false
118
- }) {
119
- return {
120
- postcssPlugin: plugin,
121
-
122
- OnceExit(css) {
123
- css.walkDecls(transform.bind(null, opts));
124
- }
125
-
126
- };
127
- }
128
-
129
- pluginCreator.postcss = true;
130
- var _default = pluginCreator;
131
- exports.default = _default;
132
- module.exports = exports.default;
@@ -1,85 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = _default;
7
- const lengthConv = {
8
- in: 96,
9
- px: 1,
10
- pt: 4 / 3,
11
- pc: 16
12
- };
13
- const timeConv = {
14
- s: 1000,
15
- ms: 1
16
- };
17
- const angleConv = {
18
- turn: 360,
19
- deg: 1
20
- };
21
-
22
- function dropLeadingZero(number) {
23
- const value = String(number);
24
-
25
- if (number % 1) {
26
- if (value[0] === '0') {
27
- return value.slice(1);
28
- }
29
-
30
- if (value[0] === '-' && value[1] === '0') {
31
- return '-' + value.slice(2);
32
- }
33
- }
34
-
35
- return value;
36
- }
37
-
38
- function transform(number, unit, conversion) {
39
- const lowerCasedUnit = unit.toLowerCase();
40
- let one, base;
41
- let convertionUnits = Object.keys(conversion).filter(u => {
42
- if (conversion[u] === 1) {
43
- one = u;
44
- }
45
-
46
- return lowerCasedUnit !== u;
47
- });
48
-
49
- if (lowerCasedUnit === one) {
50
- base = number / conversion[lowerCasedUnit];
51
- } else {
52
- base = number * conversion[lowerCasedUnit];
53
- }
54
-
55
- return convertionUnits.map(u => dropLeadingZero(base / conversion[u]) + u).reduce((a, b) => a.length < b.length ? a : b);
56
- }
57
-
58
- function _default(number, unit, {
59
- time,
60
- length,
61
- angle
62
- }) {
63
- let value = dropLeadingZero(number) + (unit ? unit : '');
64
- let converted;
65
-
66
- if (length !== false && unit.toLowerCase() in lengthConv) {
67
- converted = transform(number, unit, lengthConv);
68
- }
69
-
70
- if (time !== false && unit.toLowerCase() in timeConv) {
71
- converted = transform(number, unit, timeConv);
72
- }
73
-
74
- if (angle !== false && unit.toLowerCase() in angleConv) {
75
- converted = transform(number, unit, angleConv);
76
- }
77
-
78
- if (converted && converted.length < value.length) {
79
- value = converted;
80
- }
81
-
82
- return value;
83
- }
84
-
85
- module.exports = exports.default;