Last active
July 11, 2023 14:55
-
-
Save bennypowers/92bc5f449cd020b3e1765446a74ebd8e to your computer and use it in GitHub Desktop.
Transform a specific instance of shadow CSS to a light dom sheet, with private knowledge of the shadow dom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import postcss from 'postcss'; | |
import { readFile } from 'node:fs/promises'; | |
// load up the shadow dom css sheet, | |
// taken from the rhds git repo | |
const content = await readFile(new URL('./rh-cta.css', import.meta.url), 'utf-8'); | |
const HOST_ARGS = /:host\((?<hostArg>[^)]*)\)/g; | |
const SLOTTED_ARGS = /::slotted\((?<slottedArg>[^)]*)\)/gm; | |
// WARN: tightly coupled to private apis | |
try { | |
const processed = await postcss([ | |
{ | |
postcssPlugin: 'WRECK SHADOW CSS', | |
Comment(node) { | |
node.remove(); | |
}, | |
Rule(node) { | |
if (node.selector.match(/svg|pf-icon|rh-icon|\.icon|\.(dark|rtl)/)) { | |
node.remove(); | |
} | |
node.selector = node.selector.replace('#container:after', 'rh-cta:not(:defined):after'); | |
node.selector = node.selector.replace(/^#container$/, 'rh-cta:not(:defined)'); | |
node.selector = node.selector.replace('#container', ''); | |
if (node.selector.match(/:host/)) { | |
node.selector = node.selector.replace(HOST_ARGS, (_, args) => { | |
return `rh-cta:not(:defined)${args}`; | |
}) | |
if (node.selector === ':host') { | |
node.selector = 'rh-cta:not(:defined)'; | |
} | |
} | |
if (node.selector.match(/^::slotted/m)) { | |
node.selector = node.selector.replace(SLOTTED_ARGS, (_, args) => { | |
return `rh-cta:not(:defined) > ${args}`; | |
}) | |
} else if (node.selector.match(/::slotted/)) { | |
node.selector = node.selector.replace(SLOTTED_ARGS, (_, args) => { | |
return `> ${args}`; | |
}) | |
} | |
node.selector = | |
node.selector.replace(/^(rh-cta(.*) rh-cta (.*))$/m, 'rh-cta:not(:defined)$2 $3'); | |
}, | |
} | |
]).process(content); | |
console.log(processed.css); | |
} catch (error) { | |
console.log(error.message) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment