# All files / assets/js gfmr-editor-integration.js

0% Statements 0/141
0% Branches 0/96
0% Functions 0/33
0% Lines 0/139

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
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538

     /**
     * WP GFM Editor Integration
     *
     * Integrates with WordPress Gutenberg editor to capture and preserve
     * language information from code blocks during editing process
     *
     * @package WpGfmRenderer
     * @since 1.1.0
     */

    (function() {
        'use strict';

        // Debug utility
        const debug = (message, ...args) => {
            if (window.wpGfmDebug) {
                console.log(`[WP GFM Editor]`, message, ...args);
            }
        };

        /**
         * WP GFM Editor Integration Class
         */
        class WPGFMEditorIntegration {
            constructor() {
                this.isInitialized = false;
                this.observedBlocks = new Set();
                this.blockSubscriptions = new Map();

                debug('Editor Integration initializing...');

                // Initialize when WordPress and metadata manager are ready
                this.waitForDependencies();
            }

            /**
             * Wait for required dependencies to be available
             */
            waitForDependencies() {
                const checkDependencies = () => {
                    if (
                        typeof wp !== 'undefined' &&
                        wp.data &&
                        wp.hooks &&
                        wp.blocks &&
                        window.wpGfmMetadataManager
                    ) {
                        debug('Dependencies available, initializing...');
                        this.initialize();
                    } else {
                        debug('Waiting for dependencies...');
                        setTimeout(checkDependencies, 100);
                    }
                };

                checkDependencies();
            }

            /**
             * Initialize editor integration
             */
            initialize() {
                if (this.isInitialized) {
                    return;
                }

                try {
                    this.addBlockFilters();
                    this.subscribeToBlockChanges();
                    this.hookIntoEditorActions();

                    this.isInitialized = true;
                    debug('Editor Integration initialized successfully');
                } catch (error) {
                    console.error('[WP GFM Editor] Initialization failed:', error);
                }
            }

            /**
             * Add filters to extend block attributes with metadata
             */
            addBlockFilters() {
                // Extend code and freeform blocks with metadata attributes
                wp.hooks.addFilter(
                    'blocks.registerBlockType',
                    'gfmr-renderer/add-metadata-attributes',
                    (blockType, blockName) => {
                        if (this.isSupportedBlockType(blockName)) {
                            debug(`Adding metadata attributes to block: ${blockName}`);

                            blockType.attributes = {
                                ...blockType.attributes,
                                wpGfmLanguage: {
                                    type: 'string',
                                    default: ''
                                },
                                wpGfmOriginalLanguage: {
                                    type: 'string',
                                    default: ''
                                },
                                wpGfmCodeHash: {
                                    type: 'string',
                                    default: ''
                                },
                                wpGfmLastAnalyzed: {
                                    type: 'number',
                                    default: 0
                                }
                            };
                        }

                        return blockType;
                    }
                );
            }

            /**
             * Check if block type is supported
             */
            isSupportedBlockType(blockName) {
                const supportedTypes = [
                    'core/code',
                    'core/freeform',
                    'core/preformatted',
                    // Add custom markdown blocks if they exist
                    'wp-gfm/markdown'
                ];

                return supportedTypes.includes(blockName);
            }

            /**
             * Subscribe to block editor changes
             */
            subscribeToBlockChanges() {
                let previousBlocks = [];

                wp.data.subscribe(() => {
                    try {
                        const currentBlocks = wp.data.select('core/block-editor').getBlocks();

                        if (!currentBlocks || !Array.isArray(currentBlocks)) {
                            return;
                        }

                        // Process only when blocks have actually changed
                        if (this.blocksHaveChanged(previousBlocks, currentBlocks)) {
                            this.processBlockChanges(currentBlocks);
                            previousBlocks = this.cloneBlocks(currentBlocks);
                        }
                    } catch (error) {
                        console.warn('[WP GFM Editor] Error in block subscription:', error);
                    }
                });
            }

            /**
             * Check if blocks have changed (simplified comparison)
             */
            blocksHaveChanged(previous, current) {
                if (previous.length !== current.length) {
                    return true;
                }

                // Quick check for content changes in supported blocks
                for (let i = 0; i < current.length; i++) {
                    const currentBlock = current[i];
                    const previousBlock = previous[i];

                    if (this.isSupportedBlockType(currentBlock.name)) {
                        if (
                            !previousBlock ||
                            currentBlock.attributes.content !== previousBlock.attributes.content ||
                            currentBlock.clientId !== previousBlock.clientId
                        ) {
                            return true;
                        }
                    }
                }

                return false;
            }

            /**
             * Clone blocks for comparison (lightweight)
             */
            cloneBlocks(blocks) {
                return blocks.map(block => ({
                    clientId: block.clientId,
                    name: block.name,
                    attributes: {
                        content: block.attributes.content
                    }
                }));
            }

            /**
             * Process block changes and extract language information
             */
            processBlockChanges(blocks) {
                blocks.forEach(block => {
                    if (this.isSupportedBlockType(block.name)) {
                        this.processBlock(block);
                    }
                });
            }

            /**
             * Process individual block for language detection and metadata saving
             */
            processBlock(block) {
                try {
                    const content = block.attributes.content || '';
                    const clientId = block.clientId;

                    if (!content.trim()) {
                        return;
                    }

                    // Skip if recently analyzed
                    const lastAnalyzed = block.attributes.wpGfmLastAnalyzed || 0;
                    const now = Date.now();
                    if (now - lastAnalyzed < 1000) { // Throttle to once per second
                        return;
                    }

                    // Detect language from content
                    const languageInfo = this.detectLanguageFromContent(content, block.name);

                    if (languageInfo) {
                        debug(`Language detected for block ${clientId}:`, languageInfo);

                        // Update block attributes with metadata
                        this.updateBlockMetadata(clientId, languageInfo, content);

                        // Save to metadata manager
                        window.wpGfmMetadataManager.saveBlockMetadata(clientId, {
                            language: languageInfo.resolved,
                            originalLanguage: languageInfo.original,
                            code: content,
                            context: `editor-${block.name}`
                        });
                    }
                } catch (error) {
                    console.warn(`[WP GFM Editor] Error processing block ${block.clientId}:`, error);
                }
            }

            /**
             * Detect language from content based on block type
             */
            detectLanguageFromContent(content, blockName) {
                try {
                    if (blockName === 'core/code') {
                        // Core code block - detect from content patterns
                        return this.detectLanguageFromCodePatterns(content);
                    } else if (blockName === 'core/freeform') {
                        // Freeform/HTML block - detect from markdown syntax
                        return this.detectLanguageFromMarkdown(content);
                    } else {
                        // Other blocks - basic detection
                        return this.detectLanguageFromCodePatterns(content);
                    }
                } catch (error) {
                    console.warn('[WP GFM Editor] Language detection error:', error);
                    return null;
                }
            }

            /**
             * Detect language from markdown fenced code blocks
             */
            detectLanguageFromMarkdown(content) {
                const fencedPattern = /```(\w+)?\s*\n([\s\S]*?)\n```/g;
                const matches = Array.from(content.matchAll(fencedPattern));

                if (matches.length > 0) {
                    const match = matches[0];
                    const specifiedLang = match[1];
                    const codeContent = match[2];

                    if (specifiedLang) {
                        return {
                            original: specifiedLang,
                            resolved: this.resolveLanguageAlias(specifiedLang),
                            source: 'markdown-fenced',
                            confidence: 'high'
                        };
                    } else {
                        // No language specified, try content-based detection
                        const detectedLang = this.detectLanguageFromCodePatterns(codeContent);
                        return detectedLang ? {
                            ...detectedLang,
                            source: 'markdown-content'
                        } : null;
                    }
                }

                return null;
            }

            /**
             * Detect language from code content patterns
             */
            detectLanguageFromCodePatterns(code) {
                if (!code || code.trim().length === 0) {
                    return null;
                }

                const trimmedCode = code.trim();
                const firstLine = trimmedCode.split('\n')[0].trim();

                // JavaScript/TypeScript detection
                if (this.isJavaScript(trimmedCode, firstLine)) {
                    const isTS = this.isTypeScript(trimmedCode);
                    return {
                        original: isTS ? 'typescript' : 'javascript',
                        resolved: isTS ? 'typescript' : 'javascript',
                        source: 'content-pattern',
                        confidence: 'medium'
                    };
                }

                // Python detection
                if (this.isPython(trimmedCode, firstLine)) {
                    return {
                        original: 'python',
                        resolved: 'python',
                        source: 'content-pattern',
                        confidence: 'medium'
                    };
                }

                // PHP detection
                if (this.isPHP(trimmedCode, firstLine)) {
                    return {
                        original: 'php',
                        resolved: 'php',
                        source: 'content-pattern',
                        confidence: 'high'
                    };
                }

                // Shell/Bash detection
                if (this.isShell(trimmedCode, firstLine)) {
                    return {
                        original: 'bash',
                        resolved: 'bash',
                        source: 'content-pattern',
                        confidence: 'medium'
                    };
                }

                // CSS detection
                if (this.isCSS(trimmedCode)) {
                    return {
                        original: 'css',
                        resolved: 'css',
                        source: 'content-pattern',
                        confidence: 'medium'
                    };
                }

                // JSON detection
                if (this.isJSON(trimmedCode)) {
                    return {
                        original: 'json',
                        resolved: 'json',
                        source: 'content-pattern',
                        confidence: 'high'
                    };
                }

                return null;
            }

            /**
             * Language detection helpers
             */
            isJavaScript(code, firstLine) {
                return (
                    /^(import\s+|export\s+|const\s+\w+\s*=|let\s+\w+\s*=|var\s+\w+\s*=)/.test(firstLine) ||
                    /(function\s*\(|=>\s*{|console\.log|document\.|window\.)/.test(code) ||
                    /\.(js|jsx)$/.test(firstLine)
                );
            }

            isTypeScript(code) {
                return (
                    /\binterface\s+\w+/.test(code) ||
                    /\btype\s+\w+\s*=/.test(code) ||
                    /:\s*(string|number|boolean|any)\b/.test(code) ||
                    /\.(ts|tsx)$/.test(code)
                );
            }

            isPython(code, firstLine) {
                return (
                    /^(def\s+|class\s+|import\s+|from\s+\w+\s+import)/.test(firstLine) ||
                    /^#!\s*\/.*python/.test(firstLine) ||
                    /\bprint\s*\(/.test(code) ||
                    /\.(py|python)$/.test(firstLine)
                );
            }

            isPHP(code, firstLine) {
                return (
                    /^<\?php/.test(firstLine) ||
                    /\$\w+\s*=/.test(code) ||
                    /\becho\s+/.test(code)
                );
            }

            isShell(code, firstLine) {
                return (
                    /^#!\s*\/.*\/(bash|sh|zsh)/.test(firstLine) ||
                    /^\$\s+/.test(firstLine) ||
                    /\b(echo|ls|cd|mkdir|rm)\s/.test(code)
                );
            }

            isCSS(code) {
                return (
                    /\w+\s*\{[^}]*\}/.test(code) ||
                    /\.[a-zA-Z-]+\s*\{/.test(code) ||
                    /#[a-zA-Z-]+\s*\{/.test(code)
                );
            }

            isJSON(code) {
                try {
                    JSON.parse(code);
                    return true;
                } catch (e) {
                    return /^\s*[{[]/.test(code) && /[}\]]\s*$/.test(code);
                }
            }

            /**
             * Resolve language alias to canonical name
             */
            resolveLanguageAlias(lang) {
                const aliases = {
                    'js': 'javascript',
                    'ts': 'typescript',
                    'py': 'python',
                    'sh': 'bash',
                    'shell': 'bash',
                    'yml': 'yaml',
                    'md': 'markdown'
                };

                const normalized = lang.toLowerCase().trim();
                return aliases[normalized] || normalized;
            }

            /**
             * Update block metadata attributes
             */
            updateBlockMetadata(clientId, languageInfo, content) {
                try {
                    const codeHash = window.wpGfmMetadataManager.generateCodeHash(content);

                    wp.data.dispatch('core/block-editor').updateBlockAttributes(
                        clientId,
                        {
                            wpGfmLanguage: languageInfo.resolved,
                            wpGfmOriginalLanguage: languageInfo.original,
                            wpGfmCodeHash: codeHash,
                            wpGfmLastAnalyzed: Date.now()
                        }
                    );

                    debug(`Updated block ${clientId} metadata:`, {
                        language: languageInfo.resolved,
                        originalLanguage: languageInfo.original,
                        hash: codeHash
                    });
                } catch (error) {
                    console.warn(`[WP GFM Editor] Failed to update block metadata for ${clientId}:`, error);
                }
            }

            /**
             * Hook into editor save actions
             */
            hookIntoEditorActions() {
                // Hook into post save to ensure metadata is preserved
                wp.hooks.addAction(
                    'editor.preSavePost',
                    'gfmr-renderer/preserve-metadata',
                    this.onPreSavePost.bind(this)
                );

                wp.hooks.addAction(
                    'editor.postSavePost',
                    'gfmr-renderer/metadata-saved',
                    this.onPostSavePost.bind(this)
                );
            }

            /**
             * Handle pre-save post action
             */
            onPreSavePost() {
                debug('Pre-save post - ensuring metadata is up to date');

                try {
                    const blocks = wp.data.select('core/block-editor').getBlocks();
                    this.processBlockChanges(blocks);
                } catch (error) {
                    console.warn('[WP GFM Editor] Error in pre-save processing:', error);
                }
            }

            /**
             * Handle post-save post action
             */
            onPostSavePost() {
                debug('Post saved - metadata should be preserved');
            }
        }

        // Initialize when document is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                window.wpGfmEditorIntegration = new WPGFMEditorIntegration();
            });
        } else {
            window.wpGfmEditorIntegration = new WPGFMEditorIntegration();
        }

        // Export class for testing
        window.WPGFMEditorIntegration = WPGFMEditorIntegration;

        debug('WP GFM Editor Integration module loaded');

    })();