Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft][No ticket] New linter rule to prevent leaky selectors #2351

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');

/*
* 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, _ =>
(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;
module.exports.messages = messages;
Loading