Skip to content

Instantly share code, notes, and snippets.

@bennypowers
Last active July 11, 2023 14:55
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 bennypowers/92bc5f449cd020b3e1765446a74ebd8e to your computer and use it in GitHub Desktop.
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
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