Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created September 15, 2020 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/fa3a8940e6132aab012bdf65e4769b89 to your computer and use it in GitHub Desktop.
Save tomhodgins/fa3a8940e6132aab012bdf65e4769b89 to your computer and use it in GitHub Desktop.
import * as parseCSS from 'https://tomhodgins.github.io/parse-css/index.js'
import jsincss from 'https://unpkg.com/jsincss/index.vanilla.js'
import eunit from 'https://unpkg.com/jsincss-element-units/index.vanilla.js'
async function getAllStylesheets() {
return [...getStyleTags(), ... await getLinkedStylesheets()]
}
function getStyleTags() {
return Array.from(
document.querySelectorAll('style'),
({textContent}) => textContent
)
}
async function getLinkedStylesheets() {
const urls = Array.from(
document.querySelectorAll('link[rel="stylesheet"]'),
({href}) => href
)
const stylesheets = []
urls.forEach(async url => {
try {
const request = await fetch(url)
const text = await request.text()
stylesheets.push(text)
} catch (error) {}
})
console.log('stylesheets is', stylesheets)
return stylesheets
}
function parseElementUnits(string = '', environment = {}) {
return parseCSS.parseAStylesheet(string).value.reduce(
(output, rule) => {
if (
rule.type === 'QUALIFIED-RULE'
&& rule.toSource().match(/[\d.]--e(w|h|min|max)/)
) {
// Add rules to output JS
output.push([
rule.prelude
.map(token => token.toSource())
.join('')
.trim(),
parseCSS.parseAListOfDeclarations(
rule.value.value.map(token => token.toSource()).join('')
).filter(declaration =>
declaration.toSource().match(/[\d.]--e(w|h|min|max)/)
).map(declaration => {
// Reformat unit for runtime plugin
declaration.value
.filter(({unit}) => unit)
.forEach(token => {
token.unit = token.unit.replace(/^--/, '')
return token
})
// Stringify declaration
return declaration.toSource()
}).join(';')
])
}
return output
},
[]
)
}
// Run jsincss with the output of running all stylesheets we can load through the parser
(async () => {
const properties = parseElementUnits((await getAllStylesheets()).join('\n'))
if (properties.length) {
jsincss(event =>
properties
.map(args => eunit(...args))
.join('\n')
)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment