postcss-convert-values 5.0.3 → 5.1.1

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,11 +1,13 @@
1
1
  {
2
2
  "name": "postcss-convert-values",
3
- "version": "5.0.3",
3
+ "version": "5.1.1",
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
12
  "keywords": [
11
13
  "css",
@@ -22,6 +24,7 @@
22
24
  },
23
25
  "repository": "cssnano/cssnano",
24
26
  "dependencies": {
27
+ "browserslist": "^4.20.3",
25
28
  "postcss-value-parser": "^4.2.0"
26
29
  },
27
30
  "bugs": {
@@ -35,10 +38,5 @@
35
38
  },
36
39
  "peerDependencies": {
37
40
  "postcss": "^8.2.15"
38
- },
39
- "scripts": {
40
- "prebuild": "rimraf dist",
41
- "build": "babel src --config-file ../../babel.config.json --out-dir dist --ignore \"**/__tests__/\""
42
- },
43
- "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"
41
+ }
44
42
  }
package/src/index.js ADDED
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+ const valueParser = require('postcss-value-parser');
3
+ const browserslist = require('browserslist');
4
+ const convert = require('./lib/convert.js');
5
+
6
+ const LENGTH_UNITS = new Set([
7
+ 'em',
8
+ 'ex',
9
+ 'ch',
10
+ 'rem',
11
+ 'vw',
12
+ 'vh',
13
+ 'vmin',
14
+ 'vmax',
15
+ 'cm',
16
+ 'mm',
17
+ 'q',
18
+ 'in',
19
+ 'pt',
20
+ 'pc',
21
+ 'px',
22
+ ]);
23
+
24
+ // These properties only accept percentages, so no point in trying to transform
25
+ const notALength = new Set([
26
+ 'descent-override',
27
+ 'ascent-override',
28
+ 'font-stretch',
29
+ 'size-adjust',
30
+ 'line-gap-override',
31
+ ]);
32
+
33
+ // Can't change the unit on these properties when they're 0
34
+ const keepWhenZero = new Set([
35
+ 'stroke-dashoffset',
36
+ 'stroke-width',
37
+ 'line-height',
38
+ ]);
39
+
40
+ // Can't remove the % on these properties when they're 0 on IE 11
41
+ const keepZeroPercent = new Set(['max-height', 'height', 'min-width']);
42
+
43
+ /**
44
+ * Numbers without digits after the dot are technically invalid,
45
+ * but in that case css-value-parser returns the dot as part of the unit,
46
+ * so we use this to remove the dot.
47
+ *
48
+ * @param {string} item
49
+ * @return {string}
50
+ */
51
+ function stripLeadingDot(item) {
52
+ if (item.charCodeAt(0) === '.'.charCodeAt(0)) {
53
+ return item.slice(1);
54
+ } else {
55
+ return item;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * @param {valueParser.Node} node
61
+ * @param {Options} opts
62
+ * @param {boolean} keepZeroUnit
63
+ * @return {void}
64
+ */
65
+ function parseWord(node, opts, keepZeroUnit) {
66
+ const pair = valueParser.unit(node.value);
67
+ if (pair) {
68
+ const num = Number(pair.number);
69
+ const u = stripLeadingDot(pair.unit);
70
+ if (num === 0) {
71
+ node.value =
72
+ 0 +
73
+ (keepZeroUnit || (!LENGTH_UNITS.has(u.toLowerCase()) && u !== '%')
74
+ ? u
75
+ : '');
76
+ } else {
77
+ node.value = convert(num, u, opts);
78
+
79
+ if (
80
+ typeof opts.precision === 'number' &&
81
+ u.toLowerCase() === 'px' &&
82
+ pair.number.includes('.')
83
+ ) {
84
+ const precision = Math.pow(10, opts.precision);
85
+ node.value =
86
+ Math.round(parseFloat(node.value) * precision) / precision + u;
87
+ }
88
+ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * @param {valueParser.WordNode} node
94
+ * @return {void}
95
+ */
96
+ function clampOpacity(node) {
97
+ const pair = valueParser.unit(node.value);
98
+ if (!pair) {
99
+ return;
100
+ }
101
+ let num = Number(pair.number);
102
+ if (num > 1) {
103
+ node.value = pair.unit === '%' ? num + pair.unit : 1 + pair.unit;
104
+ } else if (num < 0) {
105
+ node.value = 0 + pair.unit;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * @param {import('postcss').Declaration} decl
111
+ * @param {string[]} browsers
112
+ * @return {boolean}
113
+ */
114
+ function shouldKeepZeroUnit(decl, browsers) {
115
+ const { parent } = decl;
116
+ const lowerCasedProp = decl.prop.toLowerCase();
117
+ return (
118
+ (decl.value.includes('%') &&
119
+ keepZeroPercent.has(lowerCasedProp) &&
120
+ browsers.includes('ie 11')) ||
121
+ (parent &&
122
+ parent.parent &&
123
+ parent.parent.type === 'atrule' &&
124
+ /** @type {import('postcss').AtRule} */ (
125
+ parent.parent
126
+ ).name.toLowerCase() === 'keyframes' &&
127
+ lowerCasedProp === 'stroke-dasharray') ||
128
+ keepWhenZero.has(lowerCasedProp)
129
+ );
130
+ }
131
+ /**
132
+ * @param {Options} opts
133
+ * @param {string[]} browsers
134
+ * @param {import('postcss').Declaration} decl
135
+ * @return {void}
136
+ */
137
+ function transform(opts, browsers, decl) {
138
+ const lowerCasedProp = decl.prop.toLowerCase();
139
+ if (
140
+ lowerCasedProp.includes('flex') ||
141
+ lowerCasedProp.indexOf('--') === 0 ||
142
+ notALength.has(lowerCasedProp)
143
+ ) {
144
+ return;
145
+ }
146
+
147
+ decl.value = valueParser(decl.value)
148
+ .walk((node) => {
149
+ const lowerCasedValue = node.value.toLowerCase();
150
+
151
+ if (node.type === 'word') {
152
+ parseWord(node, opts, shouldKeepZeroUnit(decl, browsers));
153
+ if (
154
+ lowerCasedProp === 'opacity' ||
155
+ lowerCasedProp === 'shape-image-threshold'
156
+ ) {
157
+ clampOpacity(node);
158
+ }
159
+ } else if (node.type === 'function') {
160
+ if (
161
+ lowerCasedValue === 'calc' ||
162
+ lowerCasedValue === 'min' ||
163
+ lowerCasedValue === 'max' ||
164
+ lowerCasedValue === 'clamp' ||
165
+ lowerCasedValue === 'hsl' ||
166
+ lowerCasedValue === 'hsla'
167
+ ) {
168
+ valueParser.walk(node.nodes, (n) => {
169
+ if (n.type === 'word') {
170
+ parseWord(n, opts, true);
171
+ }
172
+ });
173
+ return false;
174
+ }
175
+ if (lowerCasedValue === 'url') {
176
+ return false;
177
+ }
178
+ }
179
+ })
180
+ .toString();
181
+ }
182
+
183
+ const plugin = 'postcss-convert-values';
184
+ /**
185
+ * @typedef {{precision: boolean | number, angle?: boolean, time?: boolean, length?: boolean} & browserslist.Options} Options */
186
+ /**
187
+ * @type {import('postcss').PluginCreator<Options>}
188
+ * @param {Options} opts
189
+ * @return {import('postcss').Plugin}
190
+ */
191
+ function pluginCreator(opts = { precision: false }) {
192
+ const browsers = browserslist(null, {
193
+ stats: opts.stats,
194
+ path: __dirname,
195
+ env: opts.env,
196
+ });
197
+
198
+ return {
199
+ postcssPlugin: plugin,
200
+ OnceExit(css) {
201
+ css.walkDecls((decl) => transform(opts, browsers, decl));
202
+ },
203
+ };
204
+ }
205
+
206
+ pluginCreator.postcss = true;
207
+ 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,20 @@
1
+ export = pluginCreator;
2
+ /**
3
+ * @typedef {{precision: boolean | number, angle?: boolean, time?: boolean, length?: boolean} & browserslist.Options} 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
+ } & browserslist.Options;
19
+ declare var postcss: true;
20
+ import browserslist = require("browserslist");
@@ -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 = new Set(['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.has(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.includes('.')) {
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.includes('%') && (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.includes('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;