sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.22k stars 366 forks source link

Rule proposal: `require-css-escape` #2318

Open silverwind opened 6 months ago

silverwind commented 6 months ago

Description

CSS.escape should always be used when interpolating arbritrary variables into a CSS selector to ensure correct escaping.

Fail

document.querySelector(`#${id}`);
el.querySelectorAll(`a[href^="#${hash}"]`);

Pass

document.querySelector(`#${CSS.escape(id)}`);
el.querySelectorAll(`a[href^="#${CSS.escape(hash)}"]`);

Any tagged template should not trigger the rule:

document.querySelector(cssEscape`#${id}`);
sindresorhus commented 5 months ago

Accepted

silverwind commented 4 months ago

To reduce code churn, maybe it should have an option to limit it to attribute selectors as indicated by [ and ] in the surrounding strings. Patterns like below are pretty common and not exactly a problem if the string contains only CSS-safe characters:

const className = 'foo';
document.querySelectorAll(`.${classname}`);