postcss-ruler 1.0.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.
Files changed (4) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +286 -0
  3. package/index.js +279 -0
  4. package/package.json +54 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright 2025 Kurt Stubbings <kurt@homeworkclub.co>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,286 @@
1
+ # postcss-ruler
2
+
3
+ A PostCSS plugin that generates fluid CSS scales and values using the `clamp()` function. Create responsive typography and spacing that scales smoothly between viewport sizes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install postcss-ruler
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Add the plugin to your PostCSS configuration:
14
+
15
+ ```javascript
16
+ // postcss.config.js
17
+ module.exports = {
18
+ plugins: {
19
+ 'postcss-ruler': {
20
+ minWidth: 320, // Default minimum viewport width
21
+ maxWidth: 1760, // Default maximum viewport width
22
+ generateAllCrossPairs: false
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ Or in `.postcssrc`:
29
+
30
+ ```json
31
+ {
32
+ "plugins": {
33
+ "postcss-ruler": {
34
+ "minWidth": 320,
35
+ "maxWidth": 1760,
36
+ "generateAllCrossPairs": false
37
+ }
38
+ }
39
+ }
40
+ ```
41
+
42
+ ## Features
43
+
44
+ ### 1. At-Rule Mode: Generate Fluid Scale
45
+
46
+ Create multiple CSS custom properties from named size pairs:
47
+
48
+ ```css
49
+ @ruler scale({
50
+ minWidth: 320,
51
+ maxWidth: 1760,
52
+ prefix: 'space',
53
+ generateAllCrossPairs: false,
54
+ pairs: {
55
+ "xs": [8, 16],
56
+ "sm": [16, 24],
57
+ "md": [24, 32],
58
+ "lg": [32, 48],
59
+ "xl": [48, 64]
60
+ }
61
+ });
62
+ ```
63
+
64
+ **Generates:**
65
+
66
+ ```css
67
+ --space-xs: clamp(0.5rem, 0.4545vw + 0.3636rem, 1rem);
68
+ --space-sm: clamp(1rem, 0.4545vw + 0.8636rem, 1.5rem);
69
+ --space-md: clamp(1.5rem, 0.4545vw + 1.3636rem, 2rem);
70
+ --space-lg: clamp(2rem, 0.9091vw + 1.7273rem, 3rem);
71
+ --space-xl: clamp(3rem, 0.9091vw + 2.7273rem, 4rem);
72
+ ```
73
+
74
+ **Usage in CSS:**
75
+
76
+ ```css
77
+ .container {
78
+ padding: var(--space-md);
79
+ gap: var(--space-sm);
80
+ }
81
+ ```
82
+
83
+ #### Cross Pairs
84
+
85
+ Enable `generateAllCrossPairs: true` to create additional combinations between all defined pairs:
86
+
87
+ ```css
88
+ @ruler scale({
89
+ prefix: 'space',
90
+ generateAllCrossPairs: true,
91
+ pairs: {
92
+ "xs": [8, 16],
93
+ "md": [24, 32],
94
+ "lg": [32, 48]
95
+ }
96
+ });
97
+ ```
98
+
99
+ **Generates base pairs plus cross combinations:**
100
+
101
+ ```css
102
+ --space-xs: clamp(...);
103
+ --space-md: clamp(...);
104
+ --space-lg: clamp(...);
105
+ --space-xs-md: clamp(0.5rem, 1.3636vw + 0.3636rem, 2rem);
106
+ --space-xs-lg: clamp(0.5rem, 2.2727vw + 0.3636rem, 3rem);
107
+ --space-md-lg: clamp(1.5rem, 0.9091vw + 1.3636rem, 3rem);
108
+ ```
109
+
110
+ ### 2. Inline Mode: Fluid Function
111
+
112
+ Convert individual values directly to `clamp()` functions:
113
+
114
+ ```css
115
+ .element {
116
+ /* Uses default minWidth/maxWidth from config */
117
+ font-size: ruler.fluid(16, 24);
118
+
119
+ /* Custom viewport widths */
120
+ padding: ruler.fluid(12, 20, 320, 1200);
121
+
122
+ /* Multiple fluid values */
123
+ margin: ruler.fluid(8, 16) ruler.fluid(16, 32);
124
+ }
125
+ ```
126
+
127
+ **Generates:**
128
+
129
+ ```css
130
+ .element {
131
+ font-size: clamp(1rem, 0.4545vw + 0.8636rem, 1.5rem);
132
+ padding: clamp(0.75rem, 0.9091vw + 0.4773rem, 1.25rem);
133
+ margin: clamp(0.5rem, 0.4545vw + 0.3636rem, 1rem) clamp(1rem, 0.9091vw + 0.7273rem, 2rem);
134
+ }
135
+ ```
136
+
137
+ ## Configuration Options
138
+
139
+ ### Plugin Options
140
+
141
+ | Option | Type | Default | Description |
142
+ |--------|------|---------|-------------|
143
+ | `minWidth` | number | `320` | Default minimum viewport width in pixels |
144
+ | `maxWidth` | number | `1760` | Default maximum viewport width in pixels |
145
+ | `generateAllCrossPairs` | boolean | `false` | Generate cross-combinations in scale mode |
146
+
147
+ ### At-Rule Options
148
+
149
+ All options can be overridden per `@ruler scale()` declaration:
150
+
151
+ | Option | Type | Default | Description |
152
+ |--------|------|---------|-------------|
153
+ | `minWidth` | number | `320` | Minimum viewport width for this scale |
154
+ | `maxWidth` | number | `1760` | Maximum viewport width for this scale |
155
+ | `prefix` | string | `"space"` | Prefix for generated CSS custom properties |
156
+ | `generateAllCrossPairs` | boolean | `false` | Generate cross-combinations for this scale |
157
+ | `pairs` | object | required | Size pairs as `"name": [min, max]` |
158
+
159
+ ### Inline Function Syntax
160
+
161
+ ```
162
+ ruler.fluid(minSize, maxSize[, minWidth, maxWidth])
163
+ ```
164
+
165
+ | Parameter | Type | Required | Description |
166
+ |-----------|------|----------|-------------|
167
+ | `minSize` | number | Yes | Minimum size in pixels |
168
+ | `maxSize` | number | Yes | Maximum size in pixels |
169
+ | `minWidth` | number | No | Minimum viewport width (uses config default) |
170
+ | `maxWidth` | number | No | Maximum viewport width (uses config default) |
171
+
172
+ ## How It Works
173
+
174
+ The plugin uses linear interpolation to create fluid values that scale smoothly between viewport sizes:
175
+
176
+ 1. **Converts pixels to rem** (assumes 16px base font size)
177
+ 2. **Calculates slope**: `(maxSize - minSize) / (maxWidth - minWidth)`
178
+ 3. **Calculates y-intercept**: `-minWidth × slope + minSize`
179
+ 4. **Generates clamp**: `clamp(minRem, slopeVw + intersectRem, maxRem)`
180
+
181
+ ### Example Calculation
182
+
183
+ For `ruler.fluid(16, 24)` with default config (320-1760px):
184
+
185
+ - Slope: `(24 - 16) / (1760 - 320) = 0.005556`
186
+ - Intercept: `-320 × 0.005556 + 16 = 14.222`
187
+ - Result: `clamp(1rem, 0.5556vw + 0.8889rem, 1.5rem)`
188
+
189
+ At 320px viewport: `1rem` (16px)
190
+ At 1040px viewport: `1.3333rem` (≈21.3px)
191
+ At 1760px viewport: `1.5rem` (24px)
192
+
193
+ ## Use Cases
194
+
195
+ ### Responsive Typography
196
+
197
+ ```css
198
+ @ruler scale({
199
+ prefix: 'font',
200
+ pairs: {
201
+ "sm": [14, 16],
202
+ "base": [16, 18],
203
+ "lg": [18, 24],
204
+ "xl": [24, 32],
205
+ "2xl": [32, 48]
206
+ }
207
+ });
208
+
209
+ body {
210
+ font-size: var(--font-base);
211
+ }
212
+
213
+ h1 {
214
+ font-size: var(--font-2xl);
215
+ }
216
+
217
+ h2 {
218
+ font-size: var(--font-xl);
219
+ }
220
+ ```
221
+
222
+ ### Spacing System
223
+
224
+ ```css
225
+ @ruler scale({
226
+ prefix: 'space',
227
+ generateAllCrossPairs: true,
228
+ pairs: {
229
+ "2xs": [4, 8],
230
+ "xs": [8, 12],
231
+ "sm": [12, 16],
232
+ "md": [16, 24],
233
+ "lg": [24, 32],
234
+ "xl": [32, 48],
235
+ "2xl": [48, 64]
236
+ }
237
+ });
238
+
239
+ .section {
240
+ padding-block: var(--space-lg);
241
+ padding-inline: var(--space-md);
242
+ }
243
+
244
+ .stack > * + * {
245
+ margin-top: var(--space-sm);
246
+ }
247
+ ```
248
+
249
+ ### One-Off Fluid Values
250
+
251
+ ```css
252
+ .hero {
253
+ font-size: ruler.fluid(32, 72);
254
+ padding: ruler.fluid(24, 64);
255
+ }
256
+
257
+ .card {
258
+ border-radius: ruler.fluid(8, 16);
259
+ gap: ruler.fluid(12, 24);
260
+ }
261
+ ```
262
+
263
+ ## Browser Support
264
+
265
+ The `clamp()` function is supported in all modern browsers:
266
+ - Chrome 79+
267
+ - Firefox 75+
268
+ - Safari 13.1+
269
+ - Edge 79+
270
+
271
+ For older browsers, consider using a fallback:
272
+
273
+ ```css
274
+ .element {
275
+ font-size: 16px; /* Fallback */
276
+ font-size: ruler.fluid(16, 24);
277
+ }
278
+ ```
279
+
280
+ ## Contributing
281
+
282
+ Contributions are welcome! Please feel free to submit a Pull Request.
283
+
284
+ ## License
285
+
286
+ MIT
package/index.js ADDED
@@ -0,0 +1,279 @@
1
+ const CSSValueParser = require('postcss-value-parser');
2
+
3
+ /**
4
+ * @type {import('postcss').PluginCreator}
5
+ */
6
+ module.exports = opts => {
7
+ const DEFAULTS = {
8
+ minWidth: 320,
9
+ maxWidth: 1760,
10
+ generateAllCrossPairs: false,
11
+ };
12
+ const config = Object.assign(DEFAULTS, opts);
13
+
14
+ /**
15
+ * Converts pixels to r]em units
16
+ * @param {number} px - Pixel value to convert
17
+ * @returns {string} Rem value as string
18
+ */
19
+ const pxToRem = px => `${parseFloat((px / 16).toFixed(4))}rem`;
20
+
21
+ /**
22
+ * Validates that min value is less than max value
23
+ * @param {number} min - Minimum value
24
+ * @param {number} max - Maximum value
25
+ * @param {string} context - Context for error message
26
+ * @throws {Error} If min >= max
27
+ */
28
+ const validateMinMax = (min, max, context) => {
29
+ if (min >= max) {
30
+ throw new Error(
31
+ `[postcss-ruler] Invalid ${context}: min (${min}) must be less than max (${max})`
32
+ );
33
+ }
34
+ };
35
+
36
+ /**
37
+ * Calculates a fluid clamp() function
38
+ * @param {Object} params - Calculation parameters
39
+ * @param {number} params.minSize - Minimum size in pixels
40
+ * @param {number} params.maxSize - Maximum size in pixels
41
+ * @param {number} params.minWidth - Minimum viewport width in pixels
42
+ * @param {number} params.maxWidth - Maximum viewport width in pixels
43
+ * @returns {string} CSS clamp() function
44
+ */
45
+ const calculateClamp = ({ minSize, maxSize, minWidth, maxWidth }) => {
46
+ validateMinMax(minSize, maxSize, 'size');
47
+ validateMinMax(minWidth, maxWidth, 'width');
48
+
49
+ const slope = (maxSize - minSize) / (maxWidth - minWidth);
50
+ const intersect = -minWidth * slope + minSize;
51
+
52
+ return `clamp(${pxToRem(minSize)}, ${(slope * 100).toFixed(
53
+ 4
54
+ )}vw + ${pxToRem(intersect)}, ${pxToRem(maxSize)})`;
55
+ };
56
+
57
+ /**
58
+ * Generates clamp values from pairs
59
+ * @param {Object} params - Generation parameters
60
+ * @param {Array<{name: string, values: [number, number]}>} params.pairs - Size pairs
61
+ * @param {number} params.minWidth - Minimum viewport width
62
+ * @param {number} params.maxWidth - Maximum viewport width
63
+ * @param {boolean} params.generateAllCrossPairs - Whether to generate cross pairs
64
+ * @returns {Array<{label: string, clamp: string}>} Array of clamp values
65
+ */
66
+ const generateClamps = ({
67
+ pairs,
68
+ minWidth,
69
+ maxWidth,
70
+ generateAllCrossPairs,
71
+ }) => {
72
+ let clampScales = pairs.map(({ name, values: [minSize, maxSize] }) => ({
73
+ label: name,
74
+ clamp: calculateClamp({
75
+ minSize,
76
+ maxSize,
77
+ minWidth,
78
+ maxWidth,
79
+ }),
80
+ }));
81
+
82
+ if (generateAllCrossPairs) {
83
+ let crossPairs = [];
84
+ for (let i = 0; i < pairs.length; i++) {
85
+ for (let j = i + 1; j < pairs.length; j++) {
86
+ const [smaller, larger] = [pairs[i], pairs[j]].sort(
87
+ (a, b) => a.values[0] - b.values[0]
88
+ );
89
+ crossPairs.push({
90
+ label: `${smaller.name}-${larger.name}`,
91
+ clamp: calculateClamp({
92
+ minSize: smaller.values[0],
93
+ maxSize: larger.values[1],
94
+ minWidth,
95
+ maxWidth,
96
+ }),
97
+ });
98
+ }
99
+ }
100
+ clampScales = [...clampScales, ...crossPairs];
101
+ }
102
+
103
+ return clampScales;
104
+ };
105
+
106
+ /**
107
+ * Parses parameters from @fluid at-rule
108
+ * @param {Array} params - Parsed parameter nodes
109
+ * @returns {Object} Parsed configuration object
110
+ */
111
+ const parseAtRuleParams = params => {
112
+ const clampsParams = {
113
+ minWidth: config.minWidth,
114
+ maxWidth: config.maxWidth,
115
+ pairs: {},
116
+ relativeTo: 'viewport',
117
+ prefix: 'space',
118
+ generateAllCrossPairs: config.generateAllCrossPairs,
119
+ };
120
+
121
+ for (let i = 0; i < params.length; i++) {
122
+ const param = params[i];
123
+ const nextParam = params[i + 1];
124
+ if (!param || !nextParam) continue;
125
+ const key = param.value;
126
+ let value = nextParam.value.replace(/[:,]/g, '');
127
+
128
+ switch (key) {
129
+ case 'minWidth':
130
+ case 'maxWidth':
131
+ clampsParams[key] = Number(value);
132
+ i++;
133
+ break;
134
+ case 'prefix':
135
+ clampsParams.prefix = value.replace(/['\"]/g, '');
136
+ i++;
137
+ break;
138
+ case 'relativeTo':
139
+ clampsParams.relativeTo = value.replace(/['\"]/g, '');
140
+ i++;
141
+ break;
142
+ case 'generateAllCrossPairs':
143
+ clampsParams.generateAllCrossPairs = value === 'true';
144
+ i++;
145
+ break;
146
+ }
147
+ }
148
+
149
+ return clampsParams;
150
+ };
151
+
152
+ /**
153
+ * Extracts pairs from parsed parameters
154
+ * @param {Array} params - Parsed parameter nodes
155
+ * @returns {Object} Pairs object with name: [min, max] entries
156
+ */
157
+ const extractPairs = params => {
158
+ const pairs = {};
159
+ const pairsStartIndex = params.findIndex(x => x.value === 'pairs');
160
+
161
+ if (pairsStartIndex === -1) return pairs;
162
+
163
+ let currentName = null;
164
+ let currentValues = [];
165
+
166
+ for (let i = pairsStartIndex + 1; i < params.length; i++) {
167
+ const param = params[i];
168
+ const value = param.value.replace('[', '').replace(']', '');
169
+ if (!value || value === '[' || value === ']') continue;
170
+
171
+ if (param.type === 'string') {
172
+ if (currentName && currentValues.length === 2) {
173
+ pairs[currentName] = currentValues;
174
+ }
175
+ currentName = value;
176
+ currentValues = [];
177
+ } else {
178
+ const numValue = Number(value);
179
+ if (!isNaN(numValue)) currentValues.push(numValue);
180
+ }
181
+
182
+ if (currentName && currentValues.length === 2) {
183
+ pairs[currentName] = currentValues;
184
+ }
185
+ }
186
+
187
+ return pairs;
188
+ };
189
+
190
+ /**
191
+ * Processes @fluid at-rule and generates CSS custom properties
192
+ * @param {Object} atRule - PostCSS at-rule node
193
+ */
194
+ const processFluidAtRule = atRule => {
195
+ const { nodes } = CSSValueParser(atRule.params);
196
+ const params = nodes[0].nodes.filter(
197
+ x =>
198
+ ['word', 'string'].includes(x.type) &&
199
+ x.value !== '{' &&
200
+ x.value !== '}'
201
+ );
202
+
203
+ const clampsParams = parseAtRuleParams(params);
204
+ clampsParams.pairs = extractPairs(params);
205
+
206
+ if (Object.keys(clampsParams.pairs).length === 0) {
207
+ throw new Error(
208
+ '[postcss-ruler] No pairs defined in @ruler scale()'
209
+ );
210
+ }
211
+
212
+ const clampPairs = Object.entries(clampsParams.pairs).map(
213
+ ([name, values]) => ({ name, values })
214
+ );
215
+ const clampScale = generateClamps({
216
+ ...clampsParams,
217
+ pairs: clampPairs,
218
+ });
219
+
220
+ const response = clampScale
221
+ .map(step => `--${clampsParams.prefix}-${step.label}: ${step.clamp};`)
222
+ .join('\n');
223
+
224
+ atRule.replaceWith(response);
225
+ };
226
+
227
+ /**
228
+ * Processes inline fluid functions in declarations
229
+ * @param {Object} decl - PostCSS declaration node
230
+ */
231
+ const processFluidDeclaration = decl => {
232
+ const regex = /ruler\.fluid\(([^)]+)\)/g;
233
+ let newValue = decl.value;
234
+ let match;
235
+
236
+ while ((match = regex.exec(decl.value)) !== null) {
237
+ const args = match[1].split(',').map(s => s.trim()).map(Number);
238
+ let [minSize, maxSize, minWidth, maxWidth] = args;
239
+
240
+ minWidth = minWidth || config.minWidth;
241
+ maxWidth = maxWidth || config.maxWidth;
242
+
243
+ if (!minSize || !maxSize) {
244
+ throw new Error(
245
+ '[postcss-ruler] ruler.fluid() requires minSize and maxSize'
246
+ );
247
+ }
248
+
249
+ const clampValue = calculateClamp({
250
+ minSize,
251
+ maxSize,
252
+ minWidth,
253
+ maxWidth,
254
+ });
255
+
256
+ newValue = newValue.replace(match[0], clampValue);
257
+ }
258
+
259
+ if (newValue !== decl.value) {
260
+ decl.value = newValue;
261
+ }
262
+ };
263
+
264
+ return {
265
+ postcssPlugin: 'ruler',
266
+ AtRule: {
267
+ ruler: atRule => {
268
+ if (atRule.params.startsWith('scale(')) {
269
+ return processFluidAtRule(atRule);
270
+ }
271
+ },
272
+ },
273
+ Declaration(decl) {
274
+ processFluidDeclaration(decl);
275
+ },
276
+ };
277
+ };
278
+
279
+ module.exports.postcss = true;
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "postcss-ruler",
3
+ "version": "1.0.0",
4
+ "description": "PostCSS plugin to generate fluid scales and values.",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "README.md",
9
+ "LICENSE"
10
+ ],
11
+ "keywords": [
12
+ "postcss",
13
+ "css",
14
+ "postcss-plugin",
15
+ "postcss-ruler",
16
+ "fluid",
17
+ "clamp",
18
+ "responsive",
19
+ "typography"
20
+ ],
21
+ "scripts": {
22
+ "unit": "node --test index.test.js",
23
+ "test": "npm run unit && eslint ."
24
+ },
25
+ "author": "Kurt Stubbings <kurt@homeworkclub.co>",
26
+ "license": "MIT",
27
+ "repository": "homeworkclubco/postcss-ruler",
28
+ "engines": {
29
+ "node": ">=18.0.0"
30
+ },
31
+ "peerDependencies": {
32
+ "postcss": "^8.4.27"
33
+ },
34
+ "devDependencies": {
35
+ "eslint": "^8.47.0",
36
+ "postcss": "^8.4.27"
37
+ },
38
+ "eslintConfig": {
39
+ "parserOptions": {
40
+ "ecmaVersion": 2017
41
+ },
42
+ "env": {
43
+ "node": true,
44
+ "es6": true
45
+ },
46
+ "extends": [
47
+ "eslint:recommended"
48
+ ]
49
+ },
50
+ "dependencies": {
51
+ "postcss-value-parser": "^4.2.0",
52
+ "prettier": "^3.6.2"
53
+ }
54
+ }