prefer-heading
Ast Rule: html element
prefer-heading
const TYPES = {
string: getPropStringValue,
sequence: getPropSequenceValue,
array: getPropArrayValue,
object: getPropObjectValue,
object_element: getPropObjectValue,
functiondefinition: () => {},
};
function getTag(node) {
if (node && node.tag) {
return node.tag.value;
}
}
function getProp(attributes = [], prop = "") {
if (!prop) return;
return attributes.find((attribute) => {
if (attribute && attribute.name && attribute.name.value) {
return attribute.name.value === prop;
}
});
}
function getPropStringValue(value) {
if (value.value === "true") {
return true;
}
if (value.value === "false") {
return false;
}
return value.value.replace(/^\"/g, "").replace(/\"$/g, "");
}
function getPropArrayValue(value) {
const array = [];
const arrayElements = value.elements;
if (arrayElements.length) {
for (const element of arrayElements) {
array.push(TYPES[element.astType](element));
}
}
return array;
}
function getPropObjectValue(value) {
const object = {};
const objectElements = value.elements;
if (objectElements.length) {
for (const element of objectElements) {
object[element.name.value] = TYPES[element.value.astType](element.value);
}
}
return object;
}
function getPropSequenceValue(value) {
if (value.elements.length) {
const element = value.elements[0];
if (element) {
return TYPES[element.astType](element);
}
}
}
function extractValue(attribute, extractor) {
if (attribute) {
// Null valued attributes imply truthiness.
// For example: <div aria-hidden />
if (attribute.value === null) return true;
return extractor(attribute.value);
}
}
function getValue(value) {
return TYPES[value.astType](value);
}
function getPropValue(attribute) {
return extractValue(attribute, getValue);
}
function propHasValue(attribute) {
const value = getPropValue(attribute);
if (typeof value !== "boolean") {
return !!value;
}
return false;
}
const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"];
function visit(node, filename, code) {
const tag = getTag(node);
const asProp = getProp(node.attributes, "as");
const asValue = getPropValue(asProp);
if (tag !== "Heading" && HEADING_TAGS.includes(asValue)) {
const error = buildError(
node.start.line,
node.start.col,
node.end.line,
node.end.col,
"Prefer <Heading /> over other components.",
"INFO",
"CODE_STYLE"
);
const edits = [];
if (asValue === "h2") {
const editRemove = buildEditRemove(
asProp.start.line,
asProp.start.col,
asProp.end.line,
asProp.end.col + 1,
);
edits.push(editRemove);
}
const editUpdate = buildEditUpdate(
node.tag.start.line,
node.tag.start.col,
node.tag.end.line,
node.tag.end.col,
`Heading`
);
edits.push(editUpdate);
const fix = buildFix(
`replace ${tag} with Heading and remove as prop`,
edits
);
addError(error.addFix(fix));
}
}
bad.jsx
Expected test result: has error
good.jsx
Expected test result: no error