eslint-plugin-tailwind-canonical-classes 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Maisonnat Maxence
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, 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,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # eslint-plugin-tailwind-canonical-classes
2
+
3
+ ESLint plugin to enforce canonical Tailwind CSS class names using Tailwind CSS v4's canonicalization API.
4
+
5
+ ## Overview
6
+
7
+ This plugin helps maintain consistent Tailwind CSS class names across your codebase by automatically detecting and fixing non-canonical class names. It uses Tailwind CSS v4's `canonicalizeCandidates` API to ensure your classes follow the canonical format.
8
+
9
+ For example, it can convert:
10
+ - `p-4px` → `p-1` (if 4px equals 1rem at your root font size)
11
+ - `m-2rem` → `m-8` (if 2rem equals 8 at your scale)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install --save-dev eslint-plugin-tailwind-canonical-classes @tailwindcss/node
17
+ ```
18
+
19
+ ## Requirements
20
+
21
+ - Node.js >= 18.0.0
22
+ - ESLint >= 8.0.0
23
+ - Tailwind CSS v4
24
+ - `@tailwindcss/node` package
25
+
26
+ ## Configuration
27
+
28
+ Add the plugin to your ESLint configuration file (e.g., `eslint.config.mjs` or `.eslintrc.js`):
29
+
30
+ ### Flat Config (ESLint 9+)
31
+
32
+ ```javascript
33
+ import tailwindCanonicalClasses from 'eslint-plugin-tailwind-canonical-classes';
34
+
35
+ export default [
36
+ {
37
+ plugins: {
38
+ 'tailwind-canonical-classes': tailwindCanonicalClasses,
39
+ },
40
+ rules: {
41
+ 'tailwind-canonical-classes/tailwind-canonical-classes': [
42
+ 'warn',
43
+ {
44
+ cssPath: './app/styles/globals.css', // Path to your Tailwind CSS file
45
+ rootFontSize: 16, // Optional: root font size in pixels (default: 16)
46
+ },
47
+ ],
48
+ },
49
+ },
50
+ ];
51
+ ```
52
+
53
+ ### Legacy Config (.eslintrc.js)
54
+
55
+ ```javascript
56
+ module.exports = {
57
+ plugins: ['tailwind-canonical-classes'],
58
+ rules: {
59
+ 'tailwind-canonical-classes/tailwind-canonical-classes': [
60
+ 'warn',
61
+ {
62
+ cssPath: './app/styles/globals.css',
63
+ rootFontSize: 16,
64
+ },
65
+ ],
66
+ },
67
+ };
68
+ ```
69
+
70
+ ## Options
71
+
72
+ ### `cssPath` (required)
73
+
74
+ Type: `string`
75
+
76
+ Path to your Tailwind CSS file. Can be:
77
+ - **Relative path**: Resolved relative to your project root (where ESLint config is located)
78
+ - **Absolute path**: Full filesystem path to your CSS file
79
+
80
+ Example:
81
+ ```javascript
82
+ cssPath: './app/styles/globals.css' // Relative to project root
83
+ cssPath: '/absolute/path/to/styles.css' // Absolute path
84
+ ```
85
+
86
+ ### `rootFontSize` (optional)
87
+
88
+ Type: `number`
89
+ Default: `16`
90
+
91
+ Root font size in pixels for rem calculations. This should match your CSS root font size setting.
92
+
93
+ ## Usage
94
+
95
+ Once configured, ESLint will automatically check your JSX `className` attributes and suggest canonical alternatives.
96
+
97
+ ### Example
98
+
99
+ **Before:**
100
+ ```tsx
101
+ <div className="p-4px m-2rem">Content</div>
102
+ ```
103
+
104
+ **After auto-fix:**
105
+ ```tsx
106
+ <div className="p-1 m-8">Content</div>
107
+ ```
108
+
109
+ The plugin supports:
110
+ - String literals: `className="p-4"`
111
+ - Template literals (without expressions): `className={`p-4 ${someVar}`}` (only static parts are checked)
112
+ - JSX expression containers with static values
113
+
114
+ ## How It Works
115
+
116
+ 1. The plugin loads your Tailwind CSS file using `@tailwindcss/node`'s `__unstable__loadDesignSystem` API
117
+ 2. It extracts class names from JSX `className` attributes
118
+ 3. For each class, it uses Tailwind's `canonicalizeCandidates` to find the canonical form
119
+ 4. If a non-canonical class is found, it reports an error/warning and can auto-fix it
120
+
121
+ ## Limitations
122
+
123
+ - Only works with static class names (no dynamic expressions)
124
+ - Requires Tailwind CSS v4
125
+ - CSS file must be accessible from the ESLint process
126
+ - Template literals with expressions are skipped
127
+
128
+ ## Contributing
129
+
130
+ Contributions are welcome! Please feel free to submit a Pull Request.
131
+
132
+ ## License
133
+
134
+ MIT
135
+
136
+ ## Related
137
+
138
+ - [Tailwind CSS v4](https://tailwindcss.com/)
139
+ - [ESLint](https://eslint.org/)
140
+
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import tailwindCanonicalClasses from './lib/tailwind-canonical-classes.js';
2
+
3
+ export default {
4
+ rules: {
5
+ 'tailwind-canonical-classes': tailwindCanonicalClasses,
6
+ },
7
+ };
@@ -0,0 +1,354 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { __unstable__loadDesignSystem } from '@tailwindcss/node';
4
+
5
+ // Cache the design system to avoid reloading on every file
6
+ let designSystemCache = null;
7
+ let designSystemPromise = null;
8
+ let designSystemError = null;
9
+ let cssPathCache = null;
10
+
11
+ function resolveCssPath(cssPath, context) {
12
+ if (!cssPath) {
13
+ return null;
14
+ }
15
+
16
+ // If absolute path, use as-is
17
+ if (path.isAbsolute(cssPath)) {
18
+ return cssPath;
19
+ }
20
+
21
+ // If relative path, resolve relative to the project root (where ESLint config is)
22
+ // Try to find the project root by looking for common config files
23
+ const filename = context.getFilename();
24
+ const fileDir = path.dirname(filename);
25
+
26
+ // Try to resolve relative to the current file's directory first
27
+ const relativeToFile = path.resolve(fileDir, cssPath);
28
+ if (fs.existsSync(relativeToFile)) {
29
+ return relativeToFile;
30
+ }
31
+
32
+ // Try to resolve relative to the working directory (project root)
33
+ const relativeToCwd = path.resolve(process.cwd(), cssPath);
34
+ if (fs.existsSync(relativeToCwd)) {
35
+ return relativeToCwd;
36
+ }
37
+
38
+ return relativeToCwd; // Return even if doesn't exist, let error handling catch it
39
+ }
40
+
41
+ function getDesignSystemSync(cssPath, context) {
42
+ // Reset cache if CSS path changed
43
+ if (cssPathCache !== cssPath) {
44
+ designSystemCache = null;
45
+ designSystemPromise = null;
46
+ designSystemError = null;
47
+ cssPathCache = cssPath;
48
+ }
49
+
50
+ if (designSystemCache) {
51
+ return designSystemCache;
52
+ }
53
+
54
+ if (designSystemError) {
55
+ return null;
56
+ }
57
+
58
+ if (designSystemPromise && !designSystemCache) {
59
+ return null;
60
+ }
61
+
62
+ if (!designSystemPromise) {
63
+ try {
64
+ const resolvedPath = resolveCssPath(cssPath, context);
65
+ if (!resolvedPath || !fs.existsSync(resolvedPath)) {
66
+ designSystemError = new Error(`CSS file not found: ${cssPath}`);
67
+ return null;
68
+ }
69
+
70
+ const cssContent = fs.readFileSync(resolvedPath, 'utf-8');
71
+ const basePath = path.dirname(resolvedPath);
72
+
73
+ designSystemPromise = __unstable__loadDesignSystem(cssContent, {
74
+ base: basePath,
75
+ })
76
+ .then((ds) => {
77
+ designSystemCache = ds;
78
+ return ds;
79
+ })
80
+ .catch((error) => {
81
+ designSystemError = error;
82
+ return null;
83
+ });
84
+ } catch (error) {
85
+ designSystemError = error;
86
+ return null;
87
+ }
88
+ }
89
+
90
+ return null;
91
+ }
92
+
93
+ async function getDesignSystemAsync(cssPath, context) {
94
+ // Reset cache if CSS path changed
95
+ if (cssPathCache !== cssPath) {
96
+ designSystemCache = null;
97
+ designSystemPromise = null;
98
+ designSystemError = null;
99
+ cssPathCache = cssPath;
100
+ }
101
+
102
+ if (designSystemCache) {
103
+ return designSystemCache;
104
+ }
105
+
106
+ if (designSystemError) {
107
+ return null;
108
+ }
109
+
110
+ if (!designSystemPromise) {
111
+ getDesignSystemSync(cssPath, context);
112
+ }
113
+
114
+ if (designSystemPromise) {
115
+ try {
116
+ return await designSystemPromise;
117
+ } catch (error) {
118
+ designSystemError = error;
119
+ return null;
120
+ }
121
+ }
122
+
123
+ return null;
124
+ }
125
+
126
+ function extractClassNames(classNameValue, sourceCode) {
127
+ const classes = [];
128
+
129
+ if (!classNameValue) {
130
+ return classes;
131
+ }
132
+
133
+ if (classNameValue.type === 'Literal' && typeof classNameValue.value === 'string') {
134
+ const classString = classNameValue.value;
135
+ return classString.split(/\s+/).filter((cls) => cls.trim().length > 0);
136
+ }
137
+
138
+ if (classNameValue.type === 'TemplateLiteral') {
139
+ if (classNameValue.expressions && classNameValue.expressions.length > 0) {
140
+ return [];
141
+ }
142
+
143
+ const parts = [];
144
+ for (const quasi of classNameValue.quasis) {
145
+ const cooked = quasi.value?.cooked || '';
146
+ if (cooked.trim()) {
147
+ parts.push(cooked.trim());
148
+ }
149
+ }
150
+
151
+ const combined = parts.join(' ');
152
+ return combined.split(/\s+/).filter((cls) => cls.trim().length > 0);
153
+ }
154
+
155
+ if (classNameValue.type === 'JSXExpressionContainer') {
156
+ return extractClassNames(classNameValue.expression, sourceCode);
157
+ }
158
+
159
+ return classes;
160
+ }
161
+
162
+ export default {
163
+ meta: {
164
+ type: 'suggestion',
165
+ docs: {
166
+ description: 'Enforce canonical Tailwind CSS class names',
167
+ category: 'Best Practices',
168
+ recommended: false,
169
+ },
170
+ fixable: 'code',
171
+ schema: [
172
+ {
173
+ type: 'object',
174
+ properties: {
175
+ cssPath: {
176
+ type: 'string',
177
+ description: 'Path to your Tailwind CSS file (relative to project root or absolute)',
178
+ },
179
+ rootFontSize: {
180
+ type: 'number',
181
+ default: 16,
182
+ description: 'Root font size in pixels for rem calculations',
183
+ },
184
+ },
185
+ required: ['cssPath'],
186
+ additionalProperties: false,
187
+ },
188
+ ],
189
+ messages: {
190
+ nonCanonical: 'The class `{{original}}` can be written as `{{canonical}}`',
191
+ cssNotFound: 'CSS file not found: {{path}}. Please check your cssPath configuration.',
192
+ },
193
+ },
194
+
195
+ create(context) {
196
+ const options = context.options[0] || {};
197
+ const cssPath = options.cssPath;
198
+ const rootFontSize = options.rootFontSize || 16;
199
+ const sourceCode = context.getSourceCode();
200
+
201
+ if (!cssPath) {
202
+ context.report({
203
+ loc: { line: 1, column: 0 },
204
+ messageId: 'cssNotFound',
205
+ data: { path: 'not specified' },
206
+ });
207
+ return {};
208
+ }
209
+
210
+ return {
211
+ JSXAttribute(node) {
212
+ if (node.name.name !== 'className') {
213
+ return;
214
+ }
215
+
216
+ const value = node.value;
217
+ if (!value) {
218
+ return;
219
+ }
220
+
221
+ let classNameValue = value;
222
+ if (value.type === 'JSXExpressionContainer') {
223
+ classNameValue = value.expression;
224
+ }
225
+
226
+ if (
227
+ classNameValue.type !== 'Literal' &&
228
+ classNameValue.type !== 'TemplateLiteral' &&
229
+ classNameValue.type !== 'JSXExpressionContainer'
230
+ ) {
231
+ return;
232
+ }
233
+
234
+ const classNames = extractClassNames(classNameValue, sourceCode);
235
+ if (classNames.length === 0) {
236
+ return;
237
+ }
238
+
239
+ const designSystem = getDesignSystemSync(cssPath, context);
240
+
241
+ if (!designSystem) {
242
+ getDesignSystemAsync(cssPath, context).catch(() => {});
243
+ return;
244
+ }
245
+
246
+ if (designSystem && designSystem.canonicalizeCandidates) {
247
+ processClasses(
248
+ designSystem,
249
+ classNames,
250
+ classNameValue,
251
+ sourceCode,
252
+ rootFontSize,
253
+ context,
254
+ );
255
+ }
256
+ },
257
+ };
258
+ },
259
+ };
260
+
261
+ function processClasses(
262
+ designSystem,
263
+ classNames,
264
+ classNameValue,
265
+ sourceCode,
266
+ rootFontSize,
267
+ context,
268
+ ) {
269
+ const issues = [];
270
+
271
+ for (let i = 0; i < classNames.length; i++) {
272
+ const className = classNames[i];
273
+
274
+ try {
275
+ const canonicalized = designSystem.canonicalizeCandidates([className], {
276
+ rem: rootFontSize,
277
+ })[0];
278
+
279
+ if (canonicalized !== className) {
280
+ issues.push({
281
+ original: className,
282
+ canonical: canonicalized,
283
+ index: i,
284
+ });
285
+ }
286
+ } catch {
287
+ continue;
288
+ }
289
+ }
290
+
291
+ if (issues.length > 0) {
292
+ const originalText = sourceCode.getText(classNameValue);
293
+
294
+ const canonicalMap = new Map();
295
+ issues.forEach((issue) => {
296
+ canonicalMap.set(issue.original, issue.canonical);
297
+ });
298
+
299
+ const fixedClassNames = classNames.map((className) => {
300
+ return canonicalMap.get(className) || className;
301
+ });
302
+ const fixedClassString = fixedClassNames.join(' ');
303
+
304
+ let fixedText;
305
+
306
+ const quoteMatch = originalText.match(/^(["'`])(.*)\1$/);
307
+
308
+ if (quoteMatch) {
309
+ fixedText = `${quoteMatch[1]}${fixedClassString}${quoteMatch[1]}`;
310
+ } else if (classNameValue.type === 'TemplateLiteral') {
311
+ fixedText = `\`${fixedClassString}\``;
312
+ } else {
313
+ const startQuoteMatch = originalText.match(/^(["'`])/);
314
+ if (startQuoteMatch) {
315
+ const quote = startQuoteMatch[1];
316
+ const endQuoteIndex = originalText.lastIndexOf(quote);
317
+ if (endQuoteIndex > 0) {
318
+ fixedText = `${quote}${fixedClassString}${quote}`;
319
+ } else {
320
+ fixedText = fixedClassString;
321
+ }
322
+ } else {
323
+ fixedText = fixedClassString;
324
+ }
325
+ }
326
+
327
+ context.report({
328
+ node: classNameValue,
329
+ messageId: 'nonCanonical',
330
+ data: {
331
+ original: issues[0].original,
332
+ canonical: issues[0].canonical,
333
+ },
334
+ fix(fixer) {
335
+ if (fixedText !== originalText) {
336
+ return fixer.replaceText(classNameValue, fixedText);
337
+ }
338
+ return null;
339
+ },
340
+ });
341
+
342
+ for (let i = 1; i < issues.length; i++) {
343
+ context.report({
344
+ node: classNameValue,
345
+ messageId: 'nonCanonical',
346
+ data: {
347
+ original: issues[i].original,
348
+ canonical: issues[i].canonical,
349
+ },
350
+ });
351
+ }
352
+ }
353
+ }
354
+
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "eslint-plugin-tailwind-canonical-classes",
3
+ "version": "1.0.0",
4
+ "description": "ESLint plugin to enforce canonical Tailwind CSS class names using Tailwind CSS v4's canonicalization API",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./rule": "./lib/tailwind-canonical-classes.js"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "lib"
14
+ ],
15
+ "keywords": [
16
+ "eslint",
17
+ "eslint-plugin",
18
+ "tailwind",
19
+ "tailwindcss",
20
+ "canonical",
21
+ "lint",
22
+ "css"
23
+ ],
24
+ "author": "Maisonnat Maxence <maisonnatmax@gmail.com>",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/maxencemaisonnat/eslint-plugin-tailwind-canonical-classes.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/maxencemaisonnat/eslint-plugin-tailwind-canonical-classes/issues"
32
+ },
33
+ "homepage": "https://github.com/maxencemaisonnat/eslint-plugin-tailwind-canonical-classes#readme",
34
+ "engines": {
35
+ "node": ">=18.0.0"
36
+ },
37
+ "peerDependencies": {
38
+ "eslint": ">=8.0.0"
39
+ },
40
+ "dependencies": {
41
+ "@tailwindcss/node": "^4.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "eslint": "^9.0.0"
45
+ }
46
+ }
47
+