docusaurus/packages/docusaurus-plugin-css-cascade-layers/src/postCssPlugin.ts
Sébastien Lorber abd04a2b71
feat(theme): new CSS cascade layers plugin + built-in v4.useCssCascadeLayers future flag (#11142)
Co-authored-by: slorber <749374+slorber@users.noreply.github.com>
2025-05-22 19:55:02 +02:00

45 lines
1.1 KiB
TypeScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {findLayer} from './layers';
import type {Root, PluginCreator} from 'postcss';
import type {PluginOptions} from './options';
function wrapCssRootInLayer(root: Root, layer: string): void {
const rootBefore = root.clone();
root.removeAll();
root.append({
type: 'atrule',
name: 'layer',
params: layer,
nodes: rootBefore.nodes,
});
}
export const PostCssPluginWrapInLayer: PluginCreator<{
layers: PluginOptions['layers'];
}> = (options) => {
if (!options) {
throw new Error('PostCssPluginWrapInLayer options are mandatory');
}
const layers = Object.entries(options.layers);
return {
postcssPlugin: 'postcss-wrap-in-layer',
Once(root) {
const filePath = root.source?.input.file;
if (!filePath) {
return;
}
const layer = findLayer(filePath, layers);
if (layer) {
wrapCssRootInLayer(root, layer);
}
},
};
};
PostCssPluginWrapInLayer.postcss = true;