Skip to content

Instantly share code, notes, and snippets.

@zaydek
Last active July 15, 2023 00:59
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 zaydek/d20c3aa2515eb754674c0872af8f780c to your computer and use it in GitHub Desktop.
Save zaydek/d20c3aa2515eb754674c0872af8f780c to your computer and use it in GitHub Desktop.
import { variantImportant, variantVariables } from "@unocss/preset-mini/variants"
import { Extractor, Rule } from "unocss"
import { defineConfig } from "unocss/vite"
////////////////////////////////////////////////////////////////////////////////
// Extractors
// TODO: Get URL reference from source
// TODO: Splitting on ' and " break values such as 'tnum' and url("...")
function isValidSelector(selector: string) {
const validSelectorRe = /[!-~]+/
return validSelectorRe.test(selector)
}
// TODO: Get URL reference from source
// TODO: Splitting on ' and " break values such as 'tnum' and url("...")
function splitCode(code: string) {
return code.split(/\\?[\s'"`;{}]+/g).filter(isValidSelector) // Remove "="
}
const extractors: Extractor[] = [
{
name: "custom-splitter",
order: -1,
extract({ code }) {
return new Set(splitCode(code))
},
},
]
////////////////////////////////////////////////////////////////////////////////
// Rules
const rules: Rule[] = [
// https://regex101.com/r/dJbRwN/1
[/^((?:-|--|\$)?[a-z_]+(?:-[a-z0-9_]+)*)=(.+)$/, ([_, key, value]) => {
let isCSSVariable = false
if (key.startsWith("$")) {
isCSSVariable = true
key = `--${key.slice("$".length)}`
}
if (!key && !value) { return }
// <meta name="viewport" content="width=device-width, initial-scale=1" />
if (
key === "width" && value.startsWith("device-width") ||
key === "initial-scale" && value.startsWith("1")
) { return }
return {
[key]: value.replaceAll("_", " "),
}
}],
]
////////////////////////////////////////////////////////////////////////////////
export default defineConfig({
presets: [], // Remove UnoCSS CSS variables
extractors,
rules,
variants: [
variantImportant, // !key=value syntax
variantVariables, // [selector]:key=value syntax
],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment