@patreon/studio
Version:
Patreon Studio Design System
73 lines (59 loc) • 2 kB
JavaScript
import path from 'path';
import stylelint from 'stylelint';
const {
createPlugin,
utils: { report, ruleMessages, validateOptions },
} = stylelint;
const ruleName = 'studio/namespace-custom-properties';
const messages = ruleMessages(ruleName, {
expected: (namespace) =>
`Expected custom variables to start with "--${namespace}-" in a module named ${namespace}.module.css`,
});
// const varRegex = /var\(--(global|component)([-\w]+)\)/g;
// const tokenRegex = /token\("(.+)?"\)/g;
/** @type {import('stylelint').Rule} */
function pluginFunction(primaryOption) {
return (root, result) => {
// validate the options
const validOptions = validateOptions(result, ruleName, {
actual: primaryOption,
possible: [true, false],
});
// bail if it is not a valid option
if (!validOptions || !primaryOption) {
return;
}
// get the file path
const filePath = result.opts.from || '';
const fileName = path.basename(filePath);
// only enforce this rule if the file name ends with `.module.css`
if (!fileName.endsWith('.module.css')) {
return;
}
// get the namespace from the file name
const namespace = fileName.substring(0, fileName.length - '.module.css'.length);
// walk all the declarations
/** @param {import('stylelint').Declaration} decl */
root.walkDecls((decl) => {
const propName = decl.prop;
// bail if the prop is not a custom property
if (!propName.startsWith('--')) {
return;
}
// report if the prop does not start with the namespace
if (!propName.startsWith(`--${namespace}-`)) {
report({
message: messages.expected(namespace),
node: decl,
word: propName,
result,
ruleName,
});
}
});
};
}
pluginFunction.ruleName = ruleName;
pluginFunction.messages = messages;
// eslint-disable-next-line import/no-default-export
export default createPlugin(ruleName, pluginFunction);