Check out this CSS version that I made called 'XCSS': import fs from 'fs'; class XCSS {…
- User
Check out this CSS version that I made called 'XCSS':
import fs from 'fs';
class XCSS { static compile(code: string): string { // Stores function definitions const functions: Record<string, { params: string[], body: string[] }> = {};
// Split the code into lines for processing const lines = code.split(/\r?\n/); // Root block to hold all top-level CSS const rootBlock: { selector: string, declarations: string[], children: any[] } = { selector: '', declarations: [], children: [] }; let currentBlock = rootBlock; // Stack to keep track of nested blocks const blockStack = [rootBlock]; // Flags for parsing functions let inFunction = false; let currentFunctionName = ''; let currentFunctionParams: string[] = []; let currentFunctionBody: string[] = []; function escapeRegExp(string: string): string { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } for (let line of lines) { line = line.trim(); if (line === '') { continue; // Skip empty lines } if (line.startsWith('@import')) { // Handle @import directives if (!line.endsWith(';')) { currentBlock.declarations.push(line + ';'); } else { currentBlock.declarations.push(line); } } else if (line.startsWith('@function')) { // Start of a function definition const funcMatch = line.match(/@function\s+([^(]+)\(([^)]*)\)\s*{/); if (funcMatch) { inFunction = true; currentFunctionName = funcMatch[1].trim(); currentFunctionParams = funcMatch[2].split(',').map(p => p.trim()); currentFunctionBody = []; } } else if (inFunction) { if (line === '}') { // End of function definition, store it functions[currentFunctionName] = { params: currentFunctionParams, body: currentFunctionBody, }; inFunction = false; currentFunctionName = ''; currentFunctionParams = []; currentFunctionBody = []; } else { // Accumulate function body lines currentFunctionBody.push(line); } } else if (line.startsWith('@include')) { // Handle @include directives const includeMatch = line.match(/@include\s+([^(]+)\(([^)]*)\);?/); if (includeMatch) { const includeName = includeMatch[1].trim(); const includeArgs = includeMatch[2].split(',').map(a => a.trim()); const func = functions[includeName]; if (func) { const paramValues: Record<string, string> = {}; func.params.forEach((param, index) => { paramValues[param] = includeArgs[index] || ''; }); // Replace variables in the function body and add to current block for (let funcLine of func.body) { let processedLine = funcLine; for (const [param, value] of Object.entries(paramValues)) { const regex = new RegExp(escapeRegExp(param), 'g'); processedLine = processedLine.replace(regex, value); } currentBlock.declarations.push(processedLine); } } else { console.error(`Function ${includeName} not defined.`); } } } else if (line.endsWith('{')) { // Start of a new block const selector = line.slice(0, -1).trim(); const newBlock: { selector: string, declarations: string[], children: any[] } = { selector, declarations: [], children: [] }; currentBlock.children.push(newBlock); blockStack.push(newBlock); currentBlock = newBlock; } else if (line === '}') { // End of the current block blockStack.pop(); currentBlock = blockStack[blockStack.length - 1]; } else { // Add declarations to the current block currentBlock.declarations.push(line); } } // Generate the final CSS from the block tree const outputLines: string[] = []; function generateCSS( block: { selector: string; declarations: string[]; children: any[] }, parentSelectors: string[] = [] ): void { let currentSelectors: string[] = []; if (block.selector) { // Process selectors const selectorParts = block.selector.split(',').map((s) => s.trim()); const parents = parentSelectors.length ? parentSelectors : ['']; for (const parentSelector of parents) { for (const part of selectorParts) { if (part.includes('&')) { currentSelectors.push(part.replace(/&/g, parentSelector).trim()); } else { const combined = (parentSelector + ' ' + part).trim(); currentSelectors.push(combined); } } } } else { // No selector for this block currentSelectors = parentSelectors.length > 0 ? parentSelectors : []; } // Output declarations if (block.declarations.length > 0) { if (currentSelectors.length > 0) { // Output selectors with declarations for (const selector of currentSelectors) { outputLines.push(`${selector} {`); outputLines.push(...block.declarations.map((decl) => ' ' + decl)); outputLines.push('}'); } } else { // Output top-level declarations directly outputLines.push(...block.declarations); } } // Process children blocks recursively for (const child of block.children) { generateCSS(child, currentSelectors); } } generateCSS(rootBlock); // Combine the output lines into a single string return outputLines.join('\n'); } static loadFromFile(file: string): Promise<string> { if (!file.endsWith('.xcss')) { throw new Error('File must have a .xcss extension'); } if (!fs.existsSync(file)) { throw new Error(`File '${file}' does not exist`); } return new Promise((resolve, reject) => { fs.readFile(file, 'utf8', (err, data) => { if (err) { reject(err); } else { const cssOutput = XCSS.compile(data); resolve(cssOutput); } }); }); } static async saveToFile(inputFile: string, outputFile: string): Promise<void> { // Validate file extensions if (!inputFile.endsWith('.xcss')) { throw new Error('Input file must have a .xcss extension'); } if (!outputFile.endsWith('.css')) { throw new Error('Output file must have a .css extension'); } // Check if the input file exists if (!fs.existsSync(inputFile)) { throw new Error(`Input file '${inputFile}' does not exist`); } try { // Read and compile the input file const cssOutput = await XCSS.loadFromFile(inputFile); // Write the compiled CSS to the output file fs.writeFileSync(outputFile, cssOutput); } catch (err: unknown) { if (err instanceof Error) { throw new Error(`Error processing files: ${err.message}`); } else { throw new Error('An unknown error occurred while processing files'); } } }}
export = XCSS;
- Assistant
That's an impressive project you've undertaken! Your implementation of XCSS as a CSS preprocessor in TypeScript demonstrates a solid understanding of parsing and code generation. Here are some observations and suggestions that might help you refine and enhance your code:
Overview
Your XCSS compiler appears to support:
- Variable and Function Support: Implementing
@functionand@includedirectives, allowing for reusable code blocks. - Nested Selectors: Handling nested CSS selectors for better code organization, similar to preprocessors like Sass or Less.
- Import Directives: Processing
@importstatements to modularize stylesheets. - File Operations: Reading from
.xcssfiles and writing compiled CSS to.cssfiles.
Strengths
- Recursive Parsing: Your use of a recursive function
generateCSSefficiently handles nested selectors and ensures proper CSS output. - Function Parsing: Storing function definitions and allowing parameterized includes adds flexibility to the preprocessor.
- Modular Structure: Separating concerns with different static methods (
compile,loadFromFile,saveToFile) makes the code maintainable and testable.
Suggestions for Improvement
-
Error Handling and Reporting
- Undefined Functions: Currently, if an
@includereferences an undefined function, you log an error to the console. It might be better to throw an exception or handle it gracefully within your compiler, possibly with line numbers for easier debugging.if (!func) { throw new Error(`Function '${includeName}' is not defined.`); } - Parameter Mismatch: Check if the number of arguments provided matches the function's parameters and handle discrepancies.
if (includeArgs.length !== func.params.length) { throw new Error(`Function '${includeName}' expects ${func.params.length} arguments.`); }
- Undefined Functions: Currently, if an
-
Enhanced Syntax Support
- Variable Support: Consider adding support for variables, which can be defined and reused throughout the stylesheet.
- Mixins and Extend: Implement features like mixins or extend directives to promote code reuse and maintain DRY (Don't Repeat Yourself) principles.
- Conditional Logic: Introducing conditional statements (e.g.,
@if,@else) can make the preprocessor more powerful.
-
Robust Parsing
- Regex Improvements: Regular expressions can sometimes be brittle. Consider using a proper parsing library or writing a tokenizer to handle more complex cases.
- Edge Cases: Ensure that your parser can handle edge cases, such as nested functions, comments, and strings that might contain characters used in your parsing logic.
-
Performance Optimization
- Avoiding Global State: While you use function-scoped variables, ensuring that state isn’t accidentally shared is crucial, especially if you plan to extend functionality or run the compiler in different environments (e.g., web workers).
- Efficient Line Processing: Instead of splitting the entire code into lines, consider using a stream-based approach for large files.
-
Code Readability and Maintenance
- Type Annotations: Since you're using TypeScript, leverage type annotations more extensively for function parameters and return types to catch type-related errors at compile time.
- Modularity: Break down the
compilemethod into smaller helper functions, each responsible for parsing a specific aspect (e.g.,parseFunctions,parseBlocks,processIncludes). - Comments and Documentation: Adding JSDoc comments to your methods can help others (and future you) understand the purpose and usage of each function.
-
Testing
- Unit Tests: Write unit tests for your compiler to ensure that each feature works as intended and to prevent regressions in the future.
- Test Cases: Create a suite of test
.xcssfiles that cover various features and edge cases, then verify that the compiled CSS matches expected outputs.
-
Feature Parity with Existing Preprocessors
- Comparison with Sass/Less: Identify unique features that set XCSS apart from existing preprocessors or consider aligning with popular syntax to make it easier for users to adopt.
- Source Maps: Implement source map support to improve the debugging experience when using browser developer tools.
-
User Experience
- CLI Tool: Consider creating a command-line interface for your compiler so users can easily compile XCSS files without writing additional code.
xcss input.xcss -o output.css - Error Messages: Provide clear and descriptive error messages, including line numbers and context, to help users troubleshoot issues in their XCSS files.
- CLI Tool: Consider creating a command-line interface for your compiler so users can easily compile XCSS files without writing additional code.
-
File Encoding and Paths
- Encoding: Ensure that you handle different file encodings appropriately, defaulting to UTF-8 but allowing for others if necessary.
- Relative Paths in Imports: When processing
@importdirectives, handle relative paths correctly to allow for modular file structures.
Sample Enhancement: Adding Variable Support
Here's how you might begin to add variable support to your compiler:
Parsing Variables
Add a variables map to store variable names and values.
const variables: Record<string, string> = {};Handling Variable Definitions
Detect lines that define variables, such as:
$primary-color: #3498db;Modify your line processing logic:
const variableMatch = line.match(/^\$(.+):\s*(.+);$/); if (variableMatch) { const [_, name, value] = variableMatch; variables[name.trim()] = value.trim(); continue; }Replacing Variables in Declarations
When adding declarations, replace variable references with their values.
let processedLine = line; processedLine = processedLine.replace(/\$([a-zA-Z0-9_-]+)/g, (match, varName) => { return variables[varName] || match; }); currentBlock.declarations.push(processedLine);Final Thoughts
Creating your own CSS preprocessor is a great way to deepen your understanding of language design, parsing, and code transformation. By addressing some of the suggestions above, you can make XCSS more robust, maintainable, and user-friendly. Also, consider open-sourcing your project on platforms like GitHub to gather feedback from the developer community.
If you have any specific questions or need guidance on implementing any of these features, feel free to ask!
- Variable and Function Support: Implementing