Skip to content

Commit

Permalink
require-attrs
Browse files Browse the repository at this point in the history
  • Loading branch information
yeonjuan committed Nov 30, 2024
1 parent db4d1dd commit 67a991b
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 20 deletions.
48 changes: 28 additions & 20 deletions packages/eslint-plugin/lib/rules/require-attrs.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

const { NODE_TYPES } = require("@html-eslint/parser");
const { RULE_CATEGORY } = require("../constants");
const { createVisitors } = require("./utils/visitors");

const MESSAGE_IDS = {
MISSING: "missing",
Expand Down Expand Up @@ -103,25 +104,32 @@ module.exports = {
});
}

return {
/**
* @param {StyleTagNode | ScriptTagNode} node
* @returns
*/
[["StyleTag", "ScriptTag"].join(",")](node) {
const tagName = node.type === NODE_TYPES.StyleTag ? "style" : "script";
if (!tagOptionsMap.has(tagName)) {
return;
}
check(node, tagName);
},
Tag(node) {
const tagName = node.name.toLowerCase();
if (!tagOptionsMap.has(tagName)) {
return;
}
check(node, tagName);
},
};
/**
* @param {StyleTagNode | ScriptTagNode} node
*/
function checkStyleOrScript(node) {
const tagName = node.type === NODE_TYPES.StyleTag ? "style" : "script";
if (!tagOptionsMap.has(tagName)) {
return;
}
check(node, tagName);
}

/**
* @param {TagNode} node
*/
function checkTag(node) {
const tagName = node.name.toLowerCase();
if (!tagOptionsMap.has(tagName)) {
return;
}
check(node, tagName);
}

return createVisitors(context, {
StyleTag: checkStyleOrScript,
ScriptTag: checkStyleOrScript,
Tag: checkTag,
});
},
};
44 changes: 44 additions & 0 deletions packages/eslint-plugin/tests/rules/require-attrs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const createRuleTester = require("../rule-tester");
const rule = require("../../lib/rules/require-attrs");

const ruleTester = createRuleTester();
const templateRuleTester = createRuleTester("espree");

ruleTester.run("require-attrs", rule, {
valid: [
Expand Down Expand Up @@ -250,3 +251,46 @@ ruleTester.run("require-attrs", rule, {
},
],
});

templateRuleTester.run("[template] require-attrs", rule, {
valid: [
{
code: "html`<svg viewBox></svg>`",
options: [
{
tag: "svg",
attr: "viewBox",
},
],
},
],
invalid: [
{
code: 'html`<img class="image"/>`',
options: [
{
tag: "img",
attr: "alt",
},
{
tag: "img",
attr: "class",
value: "img",
},
],
errors: [
{
line: 1,
column: 6,
message: "Missing 'alt' attributes for 'img' tag",
},
{
line: 1,
column: 11,
endColumn: 24,
message: "Unexpected 'class' attributes value. 'img' is expected",
},
],
},
],
});

0 comments on commit 67a991b

Please sign in to comment.