|
| 1 | +import prettier from '@prettier/sync' |
| 2 | +import type { MessageIds, RuleOptions } from './types' |
| 3 | +import type { RuleModule } from '@typescript-eslint/utils/ts-eslint' |
| 4 | + |
| 5 | +const rule: RuleModule<MessageIds, RuleOptions> = { |
| 6 | + defaultOptions: [ |
| 7 | + { |
| 8 | + tabWidth: 2, |
| 9 | + }, |
| 10 | + ], |
| 11 | + meta: { |
| 12 | + type: 'layout', |
| 13 | + docs: { |
| 14 | + description: 'Enforce consistent formatting in defineStyle CSS', |
| 15 | + }, |
| 16 | + fixable: 'code', |
| 17 | + messages: { |
| 18 | + 'define-style': 'Style in defineStyle should be properly formatted', |
| 19 | + 'define-style-syntax-error': 'Syntax error in defineStyle', |
| 20 | + }, |
| 21 | + schema: [ |
| 22 | + { |
| 23 | + type: 'object', |
| 24 | + properties: { |
| 25 | + tabWidth: { |
| 26 | + type: 'number', |
| 27 | + default: 2, |
| 28 | + }, |
| 29 | + }, |
| 30 | + }, |
| 31 | + ], |
| 32 | + }, |
| 33 | + create(context) { |
| 34 | + const configuration = context.options[0] || {} |
| 35 | + const tabWidth = configuration.tabWidth || 2 |
| 36 | + return { |
| 37 | + CallExpression(node) { |
| 38 | + const callee = |
| 39 | + node.callee.type === 'MemberExpression' |
| 40 | + ? node.callee.object |
| 41 | + : node.callee |
| 42 | + const offset = callee.loc.start.column |
| 43 | + const parser = |
| 44 | + node.callee.type === 'MemberExpression' && |
| 45 | + node.callee.property.type === 'Identifier' |
| 46 | + ? node.callee.property.name |
| 47 | + : 'css' |
| 48 | + if (callee.type === 'Identifier' && callee.name === 'defineStyle') { |
| 49 | + const arg = node.arguments[0] |
| 50 | + |
| 51 | + if (arg?.type === 'TemplateLiteral') { |
| 52 | + const cssRaw = arg.quasis[0].value.raw |
| 53 | + |
| 54 | + let formattedCss = '' |
| 55 | + try { |
| 56 | + formattedCss = prettier.format(cssRaw, { parser, tabWidth }) |
| 57 | + } catch { |
| 58 | + return context.report({ |
| 59 | + node: arg, |
| 60 | + messageId: 'define-style-syntax-error', |
| 61 | + }) |
| 62 | + } |
| 63 | + |
| 64 | + const placeholder = ' '.repeat(offset + tabWidth) |
| 65 | + const result = `\n${placeholder}${formattedCss.slice(0, -1).replaceAll('\n', `\n${placeholder}`)}\n${' '.repeat(offset)}` |
| 66 | + if (result !== cssRaw) { |
| 67 | + context.report({ |
| 68 | + node: arg, |
| 69 | + messageId: 'define-style', |
| 70 | + fix(fixer) { |
| 71 | + return fixer.replaceTextRange( |
| 72 | + [arg.range[0] + 1, arg.range[1] - 1], |
| 73 | + result, |
| 74 | + ) |
| 75 | + }, |
| 76 | + }) |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + }, |
| 81 | + } |
| 82 | + }, |
| 83 | +} |
| 84 | +export default rule |
0 commit comments