Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SASS prefix handler #2016

Merged
merged 8 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/config/src/lib/addPrefixToContent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//TODO - iterate through a string and save indexes of the curly parentheses [openingIndex, closingIndex]
JetyAdam marked this conversation as resolved.
Show resolved Hide resolved
// slice the selector before that, if it's top level selector, add prefix in a scope above, if its nested, dont care

const addPrefixToContent = (content: string, sassPrefix: string): string => {
// Stack to store pairs of opening and closing curly brace indexes
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe instead of building a custom parser, we can utilise sass' compileString function? https://sass-lang.com/documentation/js-api/functions/compilestring/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. I thought maybe compileString would allow to have a more structured representation of the css, but it's just a string too.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, we don't want to compile, we will leave that to saas. We just want to not prefix css rules that match the app name. To allow styling the root element. I think is a manual process. I wish there was some nice AST for scss that is not 10 years old.

const stack: Array<[number, number | undefined]> = [];
const result: string[] = [];
let lastIndex = 0;
const prefixes = sassPrefix.split(',').map((prefix) => prefix.trim());

for (let i = 0; i < content.length; i++) {
if (content[i] === '{') {
stack.push([i, undefined]);
} else if (content[i] === '}') {
const startPair = stack.pop();
if (startPair) {
const [start] = startPair;
if (start !== undefined && stack.length === 0) {
// Top-level block
const blockContent = content.slice(start + 1, i);
const selectors = content.slice(lastIndex, start);

const shouldPrependPrefix = prefixes.every((prefix) => selectors.includes(prefix));
if (!shouldPrependPrefix) {
// Add prefix to top-level selectors
result.push(`${sassPrefix} { ${selectors} { ${blockContent} } }`);
} else {
result.push(`${selectors} { ${blockContent} }`);
}
lastIndex = i + 1; // Update lastIndex to the next character after closing brace }
}
}
}
}

// Wrap the entire content with the prefixes
return result.join(' ');
};

export default addPrefixToContent;
38 changes: 2 additions & 36 deletions packages/config/src/lib/createConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const searchIgnoredStyles = require('@redhat-cloud-services/frontend-components-config-utilities/search-ignored-styles');

import { LogType, ProxyOptions, fecLogger, proxy } from '@redhat-cloud-services/frontend-components-config-utilities';
import addPrefixToContent from './addPrefixToContent';
type Configuration = import('webpack').Configuration;
type CacheOptions = import('webpack').FileCacheOptions | import('webpack').MemoryCacheOptions;
type ProxyConfigArrayItem = import('webpack-dev-server').ProxyConfigArrayItem;
Expand Down Expand Up @@ -109,41 +110,6 @@ export const createConfig = ({
fs.writeFileSync(`${outputPath}/index.html`, template);
};

const addPrefixToContent = (content: string, sassPrefix: string | undefined, appName: string): string => {
const sassPrefixes = sassPrefix ? sassPrefix.split(',').map((prefix) => prefix.trim()) : [];

// Helper function to check if a prefix should be prepended
function shouldPrependPrefix(selector: string): boolean {
for (const prefix of sassPrefixes) {
const exactPrefix = new RegExp(`^${prefix}(\\s|\\{|$)`);
if (exactPrefix.test(selector)) {
return false;
}
}
const exactAppNamePrefix = new RegExp(`^\\.${appName}(\\s|\\{|$)`);
return !exactAppNamePrefix.test(selector);
}

function addPrefixToSelector(selector: string): string {
if (shouldPrependPrefix(selector)) {
const prefixes: string[] = sassPrefixes && sassPrefixes.length > 0 ? sassPrefixes : [`.${appName}`];
return prefixes.map((prefix: string) => `${prefix} ${selector}`).join(', ');
}
return selector;
}

// Process the content to add prefixes to all selectors
const prefixedContent = content.replace(/([^{}]+)\s*\{/g, (match, selectors) => {
const prefixedSelectors = selectors
.split(',')
.map((selector: string) => selector.trim())
.map((selector: string) => addPrefixToSelector(selector))
.join(', ');
return `${prefixedSelectors} {`;
});
return prefixedContent;
};

const devServerPort = typeof port === 'number' ? port : useProxy || standalone ? 1337 : 8002;
return {
mode: mode || (isProd ? 'production' : 'development'),
Expand Down Expand Up @@ -233,7 +199,7 @@ export const createConfig = ({
*/

if (relativePath.match(/^src/)) {
const transformedContent = addPrefixToContent(content, sassPrefix, appName);
const transformedContent = addPrefixToContent(content, sassPrefix ?? `.${appName}`);
return transformedContent;
}

Expand Down