Skip to content

Commit

Permalink
Try adding a new linter rule to prevent leaky selectors
Browse files Browse the repository at this point in the history
  • Loading branch information
futa-ikeda committed Oct 10, 2024
1 parent 5a9af29 commit c5cc0ec
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .stylelintrc.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
extends:
- stylelint-config-css-modules
- stylelint-config-sass-guidelines
plugins:
- ./ember-osf-web-stylelint
rules:
indentation: 4
max-nesting-depth: 2
Expand All @@ -13,3 +15,4 @@ rules:
- ignoreProperties:
- composes
- compose-with
ember-osf-web-stylelint-plugin/no-unlocalized-selectors: true
42 changes: 42 additions & 0 deletions ember-osf-web-stylelint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// eslint-disable @typescript-eslin/no-var-requires
const stylelint = require('stylelint');

Check failure on line 2 in ember-osf-web-stylelint.js

View workflow job for this annotation

GitHub Actions / lint

Require statement not part of import statement

Check failure on line 2 in ember-osf-web-stylelint.js

View workflow job for this annotation

GitHub Actions / lint

'require' is not defined

/*
* This rule prevents the use of bare element selectors in CSS
* Bare element selectors are selectors that are not wrapped in or paired with a class or id
*/

const ruleName = 'ember-osf-web-stylelint-plugin/no-unlocalized-selectors';
const messages = stylelint.utils.ruleMessages(ruleName, {
expected: selector => `Rule "${selector}" should be wrapped in or paired with a local-class or ID`,
});

module.exports = stylelint.createPlugin(ruleName, _ =>

Check failure on line 14 in ember-osf-web-stylelint.js

View workflow job for this annotation

GitHub Actions / lint

'module' is not defined
(postcssRoot, postcssResult) => {
postcssRoot.walkRules(rule => {
const selector = rule.selector;
const isChildRule = rule.parent.type === 'rule'; // top-level rules have rule.parent.type === 'root'
const hasGlobal = selector.includes(':global');
if (
isChildRule ||
(!hasGlobal && (selector.includes('.') || selector.includes('#'))) // has a local-class or local-id
) {
return;
}

if (
/^[a-z]+/.test(selector) || // starts with a letter
/^:global\([a-z]+/.test(selector) // or starts with :global
) {
stylelint.utils.report({
ruleName,
result: postcssResult,
message: messages.expected(selector),
node: rule,
});
}
});
});

module.exports.ruleName = ruleName;

Check failure on line 41 in ember-osf-web-stylelint.js

View workflow job for this annotation

GitHub Actions / lint

'module' is not defined
module.exports.messages = messages;

Check failure on line 42 in ember-osf-web-stylelint.js

View workflow job for this annotation

GitHub Actions / lint

'module' is not defined

0 comments on commit c5cc0ec

Please sign in to comment.