Skip to content

Commit

Permalink
Lint for reserved HTML classes (#1823)
Browse files Browse the repository at this point in the history
  • Loading branch information
neall authored Feb 22, 2023
1 parent 193e223 commit 5eadffd
Show file tree
Hide file tree
Showing 7 changed files with 468 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/ten-ravens-camp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/view-components': patch
---

Add general reserved-class-checking linter
2 changes: 1 addition & 1 deletion lib/primer/view_components/linters/base_linter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def run(processed_source)

tags.each do |tag|
next if tag.closing?
next unless self.class::TAGS&.include?(tag.name)
next if self.class::TAGS&.none?(tag.name)

classes = tag.attributes["class"]&.value&.split(" ") || []
tag_tree[tag][:offense] = false
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

require_relative "base_linter"

# Load all the other linters so we can filter out their restricted
# CLASSES—they will be responsible for complaining about the use of
# those HTML classes.
Dir[File.join(__dir__, "*.rb")].sort.each do |file|
require file unless file == __FILE__
end

module ERBLint
module Linters
# Counts the number of times a class reserved for ViewComponents is used
class DisallowComponentCssCounter < BaseLinter
CLASSES = (
JSON.parse(
File.read(
File.join(__dir__, "..", "..", "..", "..", "static", "classes.json")
)
) - BaseLinter.subclasses.reduce([]) do |html_classes, klass|
html_classes.concat(klass.const_get(:CLASSES))
end
).freeze

TAGS = nil
MESSAGE = "Primer ViewComponents defines some HTML classes with associated styles that should not be used outside those components. (These classes might have their styles changed or even disappear in the future.) Instead of using this class directly, please use its component if appropriate or define the styles you need some other way."
end
end
end
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@
"@changesets/changelog-github": "^0.4.6",
"@changesets/cli": "^2.24.1",
"@github/browserslist-config": "^1.0.0",
"@github/markdownlint-github": "^0.2.2",
"@github/prettier-config": "0.0.4",
"@github/markdownlint-github": "^0.2.2",
"@playwright/test": "^1.27.1",
"@primer/css": "20.4.7",
"@primer/primitives": "^7.11.1",
Expand Down
100 changes: 73 additions & 27 deletions script/export-css-selectors
Original file line number Diff line number Diff line change
@@ -1,37 +1,83 @@
#!/usr/bin/env node

const postcss = require('postcss');
const glob = require('glob');
const fs = require('fs');
const postcss = require('postcss')
const { readFile, writeFile } = require('node:fs/promises')
const { promisify } = require('util')
const glob = promisify(require('glob'))
const CSSwhat = require('css-what')

console.log('Exporting CSS selectors...');
console.log('Exporting CSS selectors...')

const export_selectors = (folder) => {
const exportSelectors = (folder) => {
const folder_glob = folder + '/**/*.css'
const componentNameRegex = new RegExp(`${folder.replace('/','\\/')}\\/(.*).css`)

glob(folder_glob, (_err, files) => {
files.forEach(file => {
console.log(`Processing ${file}`)
const css = fs.readFileSync(file, 'utf8')
const root = postcss.parse(css)
const componentNameRegex = new RegExp(`${folder.replace('/','\\/')}\\/(.*).css`)
const componentName = componentNameRegex.exec(file)[1]
const selectors = []

root.walkRules(rule => {
if (rule.parent.type === 'atrule' && rule.parent.name === 'keyframes') {
return
}

rule.selectors.forEach(ruleSelector => {
selectors.push(ruleSelector)
return glob(folder_glob).then(files =>
Promise.all(
files.map(async (file) => {
console.log(`Processing ${file}`)
const css = await readFile(file, 'utf8')
const root = postcss.parse(css)
const componentName = componentNameRegex.exec(file)[1]

const selectors = []
const classes = []

root.walkRules(rule => {
// @keyframes at-rules have children that look like they have normal
// CSS selectors, but they're each just "from", "to", or a percentage.
// Either way, we don't have to worry about them as selectors and they
// don't include any classes.
if (rule.parent?.type === 'atrule' && rule.parent?.name === 'keyframes') {
return
}

rule.selectors.forEach(ruleSelector => {
selectors.push(ruleSelector)
CSSwhat.parse(ruleSelector)[0].forEach(ruleObj => {
if (ruleObj.type === 'attribute' && ruleObj.name === 'class') {
classes.push(ruleObj.value)
}
})
})
})
})

fs.writeFileSync(`${file}.json`, JSON.stringify({ 'name': componentName, 'selectors': [...new Set(selectors)] }, null, 2))
})
})
console.log(`Writing ${file}.json`)
writeFile(
`${file}.json`,
JSON.stringify({
name: componentName,
selectors: [...new Set(selectors)],
classes: [...new Set(classes)]
}, null, 2)
).catch(error => console.error(`Failed to write ${file}.json`, { error }))

return classes
})
)
)
}

export_selectors('app/components/primer')
export_selectors('app/lib/primer/css')
// stylesheets under app/lib/primer/css need their individual
// json files generated
exportSelectors('app/lib/primer/css')

// class names referenced under app/components/primer might need
// to be reserved in addition to getting individual json files
const classShouldBeReserved = className =>
(className[0].toUpperCase() === className[0])
exportSelectors('app/components/primer')
.then(classLists => {
console.log(`Writing static/classes.json`)
return writeFile(
'static/classes.json',
JSON.stringify(
[...new Set(classLists.reduce((a, b) => a.concat(b)))]
.filter(classShouldBeReserved)
.sort(),
null,
2
)
)
})
.catch(error => console.error("failed to write static/classes.json", { error }))
Loading

0 comments on commit 5eadffd

Please sign in to comment.