All files / core/src/rendering css-manager.js

67.92% Statements 36/53
40% Branches 20/50
71.42% Functions 10/14
67.3% Lines 35/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                            49x               49x 49x             19x 19x     19x 1x     18x 18x     15x 2x       15x 13x     15x 15x   3x 3x               2x 1x     2x 3x     2x             5x 1x     5x   6x       6x                 3x   1x             2x                         6x 6x                             1x             17x         17x                                                                                                                              
/**
 * CSS Management System for Coherent.js
 * Handles CSS file inclusion, inline styles, and optimization
 */
 
import fs from 'node:fs/promises';
import path from 'node:path';
 
/**
 * CSS Manager Class
 * Handles CSS file loading, processing, and injection
 */
export class CSSManager {
    constructor(options = {}) {
        this.options = {
            basePath: process.cwd(),
            minify: false,
            cache: true,
            autoprefixer: false,
            ...options
        };
        
        this.cache = new Map();
        this.loadedFiles = new Set();
    }
    
    /**
     * Load CSS file content
     */
    async loadCSSFile(filePath) {
        const fullPath = path.resolve(this.options.basePath, filePath);
        const cacheKey = fullPath;
        
        // Return cached content if available
        if (this.options.cache && this.cache.has(cacheKey)) {
            return this.cache.get(cacheKey);
        }
        
        try {
            let content = await fs.readFile(fullPath, 'utf8');
            
            // Basic minification if enabled
            if (this.options.minify) {
                content = this.minifyCSS(content);
            }
            
            // Cache the content
            if (this.options.cache) {
                this.cache.set(cacheKey, content);
            }
            
            this.loadedFiles.add(filePath);
            return content;
        } catch (_error) {
            console.warn(`Failed to load CSS file: ${filePath}`, _error.message);
            return '';
        }
    }
    
    /**
     * Load multiple CSS files
     */
    async loadCSSFiles(filePaths) {
        if (!Array.isArray(filePaths)) {
            filePaths = [filePaths];
        }
        
        const cssContents = await Promise.all(
            filePaths.map(filePath => this.loadCSSFile(filePath))
        );
        
        return cssContents.join('\n');
    }
    
    /**
     * Generate CSS link tags for external files
     */
    generateCSSLinks(filePaths, baseUrl = '/') {
        if (!Array.isArray(filePaths)) {
            filePaths = [filePaths];
        }
        
        return filePaths
            .map(filePath => {
                const href = filePath.startsWith('http') 
                    ? filePath 
                    : `${baseUrl}${filePath}`.replace(/\/+/g, '/');
                
                return `<link rel="stylesheet" href="${this.escapeHtml(href)}" />`;
            })
            .join('\n');
    }
    
    /**
     * Generate inline style tag with CSS content
     */
    generateInlineStyles(cssContent) {
        if (!cssContent) return '';
        
        return `<style type="text/css">\n${cssContent}\n</style>`;
    }
    
    /**
     * Basic CSS minification
     */
    minifyCSS(css) {
        return css
            .replace(/\/\*[\s\S]*?\*\//g, '') // Remove comments
            .replace(/\s+/g, ' ') // Collapse whitespace
            .replace(/;\s*}/g, '}') // Remove last semicolon in blocks
            .replace(/{\s+/g, '{') // Remove space after opening brace
            .replace(/;\s+/g, ';') // Remove space after semicolons
            .trim();
    }
    
    /**
     * Escape HTML entities
     */
    escapeHtml(text) {
        const div = { textContent: text };
        return div.innerHTML || text;
    }
    
    /**
     * Clear cache
     */
    clearCache() {
        this.cache.clear();
        this.loadedFiles.clear();
    }
    
    /**
     * Get loaded file list
     */
    getLoadedFiles() {
        return Array.from(this.loadedFiles);
    }
}
 
/**
 * Default CSS Manager instance
 */
export const defaultCSSManager = new CSSManager();
 
/**
 * CSS processing utilities
 */
export const cssUtils = {
    /**
     * Process CSS options from render options
     */
    processCSSOptions(options = {}) {
        const {
            css = {},
            cssFiles = [],
            inlineCSS = '',
            cssLinks = [],
            cssBasePath = process.cwd(),
            cssMinify = false
        } = options;
        
        return {
            files: Array.isArray(cssFiles) ? cssFiles : [cssFiles].filter(Boolean),
            inline: inlineCSS || css.inline || '',
            links: Array.isArray(cssLinks) ? cssLinks : [cssLinks].filter(Boolean),
            basePath: css.basePath || cssBasePath,
            minify: css.minify || cssMinify,
            loadInline: css.loadInline !== false // default true
        };
    },
    
    /**
     * Generate complete CSS HTML for head section
     */
    async generateCSSHtml(cssOptions, cssManager = defaultCSSManager) {
        const cssHtmlParts = [];
        
        // Process external CSS links
        if (cssOptions.links.length > 0) {
            cssHtmlParts.push(cssManager.generateCSSLinks(cssOptions.links));
        }
        
        // Process CSS files (inline or as links)
        if (cssOptions.files.length > 0) {
            if (cssOptions.loadInline) {
                // Load and inline CSS files
                const cssContent = await cssManager.loadCSSFiles(cssOptions.files);
                if (cssContent) {
                    cssHtmlParts.push(cssManager.generateInlineStyles(cssContent));
                }
            } else {
                // Generate link tags for CSS files
                cssHtmlParts.push(cssManager.generateCSSLinks(cssOptions.files));
            }
        }
        
        // Process inline CSS
        if (cssOptions.inline) {
            cssHtmlParts.push(cssManager.generateInlineStyles(cssOptions.inline));
        }
        
        return cssHtmlParts.join('\n');
    }
};
 
/**
 * Create a new CSS Manager instance
 */
export function createCSSManager(options = {}) {
    return new CSSManager(options);
}