Last active
January 24, 2021 18:24
-
-
Save ggascoigne/1c36b661b3f7191550016886da0d29e3 to your computer and use it in GitHub Desktop.
eslint rule to ensure that formik Field elements contain an id for associated labels.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-var-requires */ | |
const { hasProp, getProp, getPropValue, elementType } = require('jsx-ast-utils') | |
/** | |
* @typedef { import("@types/eslint").RuleContext } | |
* @typedef { import("@types/eslint").RuleListener } | |
* @typedef { import("@types/eslint").ASTNode } | |
*/ | |
// eslint rule to ensure that Material UI TextField components have an id for associated labels. | |
const elements = ['Field', 'TextField'] | |
const messages = { | |
Field: 'Formik Fields that specify a label must also specify an id', | |
TextField: 'TextFields that specify a label must also specify an id', | |
} | |
module.exports = { | |
meta: { | |
type: 'problem', | |
fixable: 'code', | |
schema: [], // no options | |
}, | |
create(context) { | |
return { | |
/** | |
* @param {ASTNode} node | |
* @return RuleListener | |
*/ | |
JSXOpeningElement(node) { | |
elements.forEach((element) => { | |
if (elementType(node) === element) { | |
if ( | |
hasProp(node.attributes, 'label') && | |
!hasProp(node.attributes, 'id') | |
) { | |
context.report({ | |
node: node.name, | |
message: messages[element], | |
fix(fixer) { | |
const nameProp = getProp(node.attributes, 'name') | |
const nameValue = getPropValue(nameProp) | |
if (nameValue) { | |
const valueCode = context | |
.getSourceCode() | |
.getText(nameProp.value) | |
return [ | |
fixer.insertTextBefore( | |
node.attributes[0], | |
`id=${valueCode} ` | |
), | |
] | |
} else { | |
return undefined | |
} | |
}, | |
}) | |
} | |
} | |
}) | |
}, | |
} | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment