# All files / assets/js gfmr-admin-settings.js

0% Statements 0/83
0% Branches 0/40
0% Functions 0/13
0% Lines 0/83

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

     /**
     * GFMR Admin Settings Page JavaScript
     *
     * Handles theme preview and settings page interactions.
     *
     * @package MarkdownRendererForGitHub
     * @since 1.8.0
     */

    (function($) {
    	'use strict';

    	$(document).ready(function() {
    		const previewContainer = $('#gfmr-theme-preview');
    		const previewCode = $('#gfmr-preview-code');
    		const themeDisplay = $('#gfmr-theme-display');

    		// Exit if not on settings page
    		if (previewContainer.length === 0) {
    			return;
    		}

    		let isHighlightingInitialized = false;
    		const originalCodeContent = previewCode.text();

    		// Get localized data from PHP
    		const gfmrAdminSettings = window.gfmrAdminSettings || {};
    		const optionName = gfmrAdminSettings.optionName || 'gfmr_theme_settings';
    		const i18n = gfmrAdminSettings.i18n || {
    			light: 'Light',
    			dark: 'Dark',
    			system: 'System',
    			applyingTheme: 'Applying theme...'
    		};

    		// Shiki theme mapping for admin preview
    		const shikiThemeMapping = {
    			light: 'github-light',
    			dark: 'github-dark',
    			system: 'auto'
    		};

    		/**
    		 * Check system theme preference
    		 *
    		 * @return {string} Shiki theme name based on system preference
    		 */
    		function getSystemTheme() {
    			const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    			console.log('GFMR Admin Preview: System prefers', prefersDark ? 'dark' : 'light', 'theme');
    			return prefersDark ? 'github-dark' : 'github-light';
    		}

    		/**
    		 * Get effective Shiki theme based on selection
    		 *
    		 * @param {string} selectedTheme - The user-selected theme option
    		 * @return {string} Effective Shiki theme name
    		 */
    		function getEffectiveShikiTheme(selectedTheme) {
    			if (selectedTheme === 'system') {
    				return getSystemTheme();
    			}
    			return shikiThemeMapping[selectedTheme] || 'github-light';
    		}

    		/**
    		 * Initialize Shiki highlighting for admin preview
    		 */
    		function initializeHighlighting() {
    			if (isHighlightingInitialized) {
    				return;
    			}

    			try {
    				console.log('GFMR Admin Preview: Initializing with basic syntax highlighting...');

    				// Mark as initialized to avoid retry
    				isHighlightingInitialized = true;

    				// Apply basic syntax highlighting immediately
    				applyBasicSyntaxHighlighting();

    				// Apply initial theme styling
    				const currentTheme = previewContainer.data('current-theme');
    				updateThemePreview(currentTheme, false);

    				console.log('GFMR Admin Preview: Basic highlighting initialized');

    			} catch (error) {
    				console.warn('GFMR Admin Preview: Error initializing highlighting', error);
    				isHighlightingInitialized = true;
    			}
    		}

    		/**
    		 * Apply basic syntax highlighting with proper HTML handling
    		 */
    		function applyBasicSyntaxHighlighting() {
    			try {
    				const code = originalCodeContent;

    				// Apply syntax highlighting first (before HTML escaping)
    				let highlightedCode = code
    					.replace(/\/\/(.*)/g, '##COMMENT_START##$1##COMMENT_END##')
    					.replace(/\b(const|let|var|function|return|if|else|for|while|class|async|await)\b/g, '##KEYWORD_START##$1##KEYWORD_END##')
    					.replace(/\b(console|window|document|Array|Object)\b/g, '##PROPERTY_START##$1##PROPERTY_END##')
    					.replace(/(['"`])((?:\\.|(?!\1)[^\\])*?)\1/g, '##STRING_START##$1$2$1##STRING_END##')
    					.replace(/\b(\d+)\b/g, '##NUMBER_START##$1##NUMBER_END##');

    				// Now safely escape HTML entities
    				highlightedCode = highlightedCode
    					.replace(/&/g, '&amp;')
    					.replace(/</g, '&lt;')
    					.replace(/>/g, '&gt;')
    					.replace(/"/g, '&quot;')
    					.replace(/'/g, '&#x27;');

    				// Convert markers to proper HTML spans
    				highlightedCode = highlightedCode
    					.replace(/##COMMENT_START##/g, '<span class="gfmr-comment">')
    					.replace(/##COMMENT_END##/g, '</span>')
    					.replace(/##KEYWORD_START##/g, '<span class="gfmr-keyword">')
    					.replace(/##KEYWORD_END##/g, '</span>')
    					.replace(/##PROPERTY_START##/g, '<span class="gfmr-property">')
    					.replace(/##PROPERTY_END##/g, '</span>')
    					.replace(/##STRING_START##/g, '<span class="gfmr-string">')
    					.replace(/##STRING_END##/g, '</span>')
    					.replace(/##NUMBER_START##/g, '<span class="gfmr-number">')
    					.replace(/##NUMBER_END##/g, '</span>');

    				// Update preview with properly structured HTML
    				$('#gfmr-preview-wrapper').html(
    					'<pre class="gfmr-admin-preview"><code>' + highlightedCode + '</code></pre>'
    				);
    				console.log('GFMR Admin Preview: Applied basic syntax highlighting');

    			} catch (error) {
    				console.warn('GFMR Admin Preview: Basic highlighting failed', error);
    				// Fallback to plain text with proper escaping
    				const escapedFallback = originalCodeContent
    					.replace(/&/g, '&amp;')
    					.replace(/</g, '&lt;')
    					.replace(/>/g, '&gt;')
    					.replace(/"/g, '&quot;')
    					.replace(/'/g, '&#x27;');
    				$('#gfmr-preview-wrapper').html(
    					'<pre class="gfmr-admin-preview"><code>' + escapedFallback + '</code></pre>'
    				);
    			}
    		}

    		/**
    		 * Update theme preview display
    		 *
    		 * @param {string} theme - Theme to preview
    		 * @param {boolean} applyHighlighting - Whether to reapply highlighting
    		 */
    		function updateThemePreview(theme, applyHighlighting) {
    			// Update preview container data attribute
    			previewContainer.attr('data-preview-theme', theme);

    			console.log('GFMR Admin Preview: Updating theme preview to:', theme);

    			// Always reapply basic syntax highlighting when theme changes
    			if (applyHighlighting && isHighlightingInitialized) {
    				applyBasicSyntaxHighlighting();
    			}

    			// Add visual feedback during theme switching
    			previewContainer.addClass('gfmr-theme-switching');

    			setTimeout(function() {
    				previewContainer.removeClass('gfmr-theme-switching');
    			}, 600);
    		}

    		/**
    		 * Update theme display text
    		 *
    		 * @param {string} theme - Selected theme
    		 */
    		function updateThemeDisplay(theme) {
    			const themeNames = {
    				'light': i18n.light,
    				'dark': i18n.dark,
    				'system': i18n.system
    			};
    			themeDisplay.text(themeNames[theme] || theme);
    		}

    		// Expose getEffectiveShikiTheme for potential external use
    		window.gfmrGetEffectiveShikiTheme = getEffectiveShikiTheme;

    		// Start initialization
    		setTimeout(initializeHighlighting, 500);

    		// Handle theme selection changes
    		$('input[name="' + optionName + '[theme]"]').on('change', function() {
    			const selectedTheme = $(this).val();
    			updateThemePreview(selectedTheme, true);
    			updateThemeDisplay(selectedTheme);
    		});

    		// System theme detection
    		if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    			console.log('GFMR Admin Preview: System prefers dark theme');
    		} else {
    			console.log('GFMR Admin Preview: System prefers light theme');
    		}

    		// Handle system theme changes for 'system' option
    		if (window.matchMedia) {
    			const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
    			darkModeQuery.addEventListener('change', function() {
    				const currentSelection = $('input[name="' + optionName + '[theme]"]:checked').val();
    				if (currentSelection === 'system') {
    					updateThemePreview('system', true);
    				}
    			});
    		}

    		/**
    		 * Tab switching functionality
    		 */
    		const form = $('#gfmr-settings-form');
    		let hiddenInput = form.find('input[name="gfmr_active_tab"]');
    		if (hiddenInput.length === 0) {
    			hiddenInput = $('<input>').attr({
    				type: 'hidden',
    				name: 'gfmr_active_tab'
    			});
    			form.append(hiddenInput);
    		}

    		function switchTab(tabId) {
    			// Hide all tab contents
    			$('.gfmr-tab-content').hide();

    			// Remove active class from all tabs
    			$('.nav-tab').removeClass('nav-tab-active');

    			// Show selected tab content
    			$('#tab-' + tabId).show();

    			// Add active class to clicked tab
    			$('.nav-tab[data-tab="' + tabId + '"]').addClass('nav-tab-active');

    			// Update hidden input
    			hiddenInput.val(tabId);

    			// Update URL hash without scrolling
    			history.replaceState(null, null, '#tab-' + tabId);
    		}

    		// Tab click event handler
    		$('.nav-tab').on('click', function(e) {
    			e.preventDefault();
    			const tabId = $(this).data('tab');
    			switchTab(tabId);
    		});

    		// Restore active tab from URL hash on page load
    		const urlHash = window.location.hash;
    		if (urlHash && urlHash.startsWith('#tab-')) {
    			const tabId = urlHash.substring(5); // Remove '#tab-' prefix
    			switchTab(tabId);
    		}
    	});
    })(jQuery);