All files / assets/js gfmr-charts.js

86.76% Statements 118/136
74.66% Branches 56/75
84.21% Functions 16/19
87.4% Lines 118/135

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392              1x         69x 69x 69x     69x           69x                         1x                 29x                           20x     20x 29x 29x 26x 9x 17x   16x     29x       20x                                                     20x     20x               6x   6x     6x     6x     6x 6x 6x 6x 6x       6x 6x 6x   6x 6x   6x 6x 6x 6x 6x 6x                 12x 2x     10x       10x 10x 10x 10x 10x                                             10x               22x   22x 3x             19x             12x 12x   10x 1x   9x 1x     8x         8x   4x               13x 1x     12x   12x 12x 12x     12x 1x 1x     11x       11x     11x 11x   11x 11x   11x     11x 11x 3x     11x   10x 10x     10x 10x     1x 1x               4x 4x     4x 4x   4x   4x             4x 4x 3x     4x             5x 5x 5x           5x 5x 3x               13x 13x 13x               7x           7x   7x 6x   6x   6x 6x 5x   1x                                     1x 1x      
/**
 * GFMR Charts Module
 * Chart.js integration for WordPress (UMD version)
 *
 * @package WpGfmRenderer
 * @since 2.1.0
 */
(function(global) {
    'use strict';
 
    class WPGFMCharts {
        constructor() {
            this.chartjsLoaded = false;
            this.chartjsLoadPromise = null;
            this.processedCharts = new WeakSet();
 
            // All supported chart types (all free)
            this.supportedTypes = new Set([
                'line', 'bar', 'pie', 'doughnut',
                'scatter', 'bubble', 'radar', 'polarArea'
            ]);
 
            // Chart configuration defaults
            this.defaultConfig = {
                responsive: true,
                maintainAspectRatio: true,
                animation: { duration: 750 }
            };
        }
 
        /**
         * Get current theme mode
         * Charts always use light mode for consistency
         */
        isDarkTheme() {
            // Charts always use light mode
            return false;
        }
 
        /**
         * Get theme colors for charts
         * Charts always use light theme colors for consistency
         */
        getThemeColors() {
            // Charts always use light theme colors
            return {
                text: '#24292f',
                grid: '#d0d7de',
                border: '#d0d7de'
            };
        }
 
        /**
         * Merge theme colors into chart config options
         * Preserves user-specified colors, applies theme colors only where unspecified
         * @param {Object} config - Chart.js configuration object
         * @returns {Object} Object containing isDark and colors for container styling
         */
        mergeThemeColors(config) {
            const colors = this.getThemeColors();
 
            // Deep merge helper - preserves user-specified values
            const deepMerge = (target, source) => {
                const result = { ...target };
                for (const key in source) {
                    if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
                        result[key] = deepMerge(target[key] || {}, source[key]);
                    } else if (target[key] === undefined) {
                        // Only apply source value if target doesn't have it
                        result[key] = source[key];
                    }
                }
                return result;
            };
 
            // Theme options (applied only if not user-specified)
            const themeOptions = {
                color: colors.text,
                borderColor: colors.border,
                scales: {
                    x: {
                        grid: { color: colors.grid },
                        ticks: { color: colors.text }
                    },
                    y: {
                        grid: { color: colors.grid },
                        ticks: { color: colors.text }
                    }
                },
                plugins: {
                    legend: { labels: { color: colors.text } },
                    title: { color: colors.text },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: colors.text,
                        bodyColor: colors.text,
                        borderColor: colors.border,
                        borderWidth: 1
                    }
                }
            };
 
            // Merge: user options override theme options
            config.options = deepMerge(themeOptions, config.options || {});
 
            // Charts always use light mode
            return { isDark: false, colors };
        }
 
        /**
         * Apply theme colors to Chart.js global defaults
         * Charts always use light theme colors
         */
        applyThemeToDefaults() {
            Iif (!global.Chart) return;
 
            const colors = this.getThemeColors();
 
            // Global text color
            global.Chart.defaults.color = colors.text;
 
            // Global border color
            global.Chart.defaults.borderColor = colors.border;
 
            // Scale defaults (affects all axes)
            Eif (global.Chart.defaults.scale) {
                global.Chart.defaults.scale.grid = global.Chart.defaults.scale.grid || {};
                global.Chart.defaults.scale.grid.color = colors.grid;
                global.Chart.defaults.scale.ticks = global.Chart.defaults.scale.ticks || {};
                global.Chart.defaults.scale.ticks.color = colors.text;
            }
 
            // Plugins
            Eif (global.Chart.defaults.plugins) {
                Eif (global.Chart.defaults.plugins.legend?.labels) {
                    global.Chart.defaults.plugins.legend.labels.color = colors.text;
                }
                Eif (global.Chart.defaults.plugins.title) {
                    global.Chart.defaults.plugins.title.color = colors.text;
                }
                Eif (global.Chart.defaults.plugins.tooltip) {
                    global.Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(255, 255, 255, 0.95)';
                    global.Chart.defaults.plugins.tooltip.titleColor = colors.text;
                    global.Chart.defaults.plugins.tooltip.bodyColor = colors.text;
                    global.Chart.defaults.plugins.tooltip.borderColor = colors.border;
                    global.Chart.defaults.plugins.tooltip.borderWidth = 1;
                }
            }
        }
 
        /**
         * Load Chart.js library (UMD version)
         */
        async ensureChartJSLoaded() {
            if (this.chartjsLoaded && global.Chart) {
                return global.Chart;
            }
 
            Iif (this.chartjsLoadPromise) {
                return this.chartjsLoadPromise;
            }
 
            this.chartjsLoadPromise = new Promise((resolve, reject) => {
                Eif (global.Chart) {
                    this.chartjsLoaded = true;
                    resolve(global.Chart);
                    return;
                }
 
                const script = document.createElement('script');
                // UMD version
                script.src = global.wpGfmBuildAssetUrl('assets/libs/chartjs/chart.umd.min.js');
 
                script.onload = () => {
                    this.chartjsLoaded = true;
                    console.log('[GFMR Charts] Chart.js UMD loaded');
                    // Apply theme defaults after Chart.js is loaded
                    this.applyThemeToDefaults();
                    resolve(global.Chart);
                };
 
                script.onerror = (error) => {
                    console.error('[GFMR Charts] Failed to load Chart.js:', error);
                    reject(error);
                };
 
                document.head.appendChild(script);
            });
 
            return this.chartjsLoadPromise;
        }
 
        /**
         * Check if chart type is supported
         */
        isChartAllowed(element, config) {
            // All chart types are allowed (no Pro/Free distinction)
            const chartType = config.type;
 
            if (!this.supportedTypes.has(chartType)) {
                return {
                    allowed: false,
                    reason: 'unsupported_type',
                    message: `Unsupported chart type: ${chartType}`
                };
            }
 
            return { allowed: true };
        }
 
        /**
         * Parse chart configuration from JSON
         */
        parseChartConfig(content) {
            try {
                const config = JSON.parse(content);
 
                if (!config.type) {
                    throw new Error('Chart type is required');
                }
                if (!config.data) {
                    throw new Error('Chart data is required');
                }
 
                config.options = {
                    ...this.defaultConfig,
                    ...(config.options || {})
                };
 
                return config;
            } catch (error) {
                throw new Error(`Invalid chart config: ${error.message}`);
            }
        }
 
        /**
         * Render a single chart
         */
        async renderChart(element, config) {
            if (this.processedCharts.has(element)) {
                return;
            }
 
            try {
                // Fence-priority check
                const checkResult = this.isChartAllowed(element, config);
                Eif (global.wpGfmConfig?.debug) {
                    console.log('[GFMR Charts] Permission check:', config.type, checkResult.allowed ? 'allowed' : checkResult.reason);
                }
 
                if (!checkResult.allowed) {
                    this.renderBlockedMessage(element, checkResult);
                    return;
                }
 
                const Chart = await this.ensureChartJSLoaded();
 
                // Merge theme colors into config (preserves user-specified colors)
                // Charts always use light mode
                this.mergeThemeColors(config);
 
                // Create container (light theme fixed)
                const container = document.createElement('div');
                container.className = 'gfmr-chart-container';
 
                const canvas = document.createElement('canvas');
                canvas.id = 'gfmr-chart-' + Date.now() + '-' +
                    Math.random().toString(36).substr(2, 9);
                container.appendChild(canvas);
 
                // Replace original element
                const targetElement = element.closest('pre') || element.parentElement;
                if (targetElement?.parentNode) {
                    targetElement.parentNode.replaceChild(container, targetElement);
                }
 
                new Chart(canvas.getContext('2d'), config);
 
                Eif (global.wpGfmConfig?.debug) {
                    console.log('[GFMR Charts] Chart rendered:', config.type);
                }
 
                this.processedCharts.add(container);
                container.setAttribute('data-gfmr-processed', 'true');
 
            } catch (error) {
                console.error('[GFMR Charts] Render error:', error);
                this.renderErrorMessage(element, error.message);
            }
        }
 
        /**
         * Render blocked message (unsupported chart type)
         */
        renderBlockedMessage(element, checkResult) {
            Eif (global.wpGfmConfig?.debug) {
                console.log('[GFMR Charts] Rendering blocked message:', checkResult.reason);
            }
 
            const container = document.createElement('div');
            container.className = 'gfmr-chart-blocked';
 
            const message = checkResult.message || 'Chart not available';
 
            container.innerHTML = `
                <div class="gfmr-chart-error-content">
                    <div class="gfmr-chart-error-icon">📊</div>
                    <strong>${this.escapeHtml(message)}</strong>
                </div>
            `;
 
            const targetElement = element.closest('pre') || element.parentElement;
            if (targetElement?.parentNode) {
                targetElement.parentNode.replaceChild(container, targetElement);
            }
 
            this.processedCharts.add(container);
        }
 
        /**
         * Render error message
         */
        renderErrorMessage(element, message) {
            const container = document.createElement('div');
            container.className = 'gfmr-chart-error';
            container.innerHTML = `
                <div class="gfmr-chart-error-content">
                    <strong>Chart Error:</strong> ${this.escapeHtml(message)}
                </div>
            `;
 
            const targetElement = element.closest('pre') || element.parentElement;
            if (targetElement?.parentNode) {
                targetElement.parentNode.replaceChild(container, targetElement);
            }
        }
 
        /**
         * HTML escape utility
         */
        escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
 
        /**
         * Find and process all chart blocks
         */
        async processAllCharts() {
            // Search for both chart and chart-pro (exclude processed)
            const chartBlocks = document.querySelectorAll(
                'code[class*="language-chart"]:not([data-gfmr-chart-processed]), ' +
                'code.language-chart:not([data-gfmr-chart-processed]), ' +
                'code.language-chart-pro:not([data-gfmr-chart-processed])'
            );
 
            console.log(`[GFMR Charts] Found ${chartBlocks.length} chart blocks`);
 
            for (const block of chartBlocks) {
                block.setAttribute('data-gfmr-chart-processed', 'true');
 
                const content = block.textContent || '';
 
                try {
                    const config = this.parseChartConfig(content);
                    await this.renderChart(block, config);
                } catch (error) {
                    this.renderErrorMessage(block, error.message);
                }
            }
        }
    }
 
    // Initialize and export
    function initializeCharts() {
        const charts = new WPGFMCharts();
        global.wpGfmCharts = charts;
 
        // If Chart.js is already loaded, apply theme defaults
        if (global.Chart) {
            charts.applyThemeToDefaults();
        }
 
        return charts;
    }
 
    global.WPGFMCharts = WPGFMCharts;
    global.wpGfmInitializeCharts = initializeCharts;
 
})(typeof window !== 'undefined' ? window : global);