MediaWiki:Common.js

From Psalms: Layer by Layer
Jump to: navigation, search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */

// Function to check if all <pre class="mermaid"> elements are processed
function checkMermaidProcessed() {
    var mermaidPreElements = document.querySelectorAll('pre.mermaid');
    var allProcessed = true;

    mermaidPreElements.forEach(function (element) {
        if (!element.hasAttribute('data-processed') || element.getAttribute('data-processed') !== 'true') {
            allProcessed = false;
        }
    });

    return allProcessed;
}

// Function to wait until all Mermaid diagrams are processed
function waitForMermaidProcessing(callback) {
    var interval = setInterval(function () {
        if (checkMermaidProcessed()) {
            clearInterval(interval);
            callback(); // Once all elements are processed, run the callback
        }
    }, 100); // Check every 100ms
}

function toggleVisibility(containerId, className) {
    //console.log("Toggling visibility for " + className + " in " + containerId);
    var container = document.getElementById(containerId);
    if (container) {
        var elements = container.querySelectorAll("g." + className);
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            
            if (element.style.display === "none") {
                element.style.display = ""; // Show element
            } else {
                element.style.display = "none"; // Hide element
            }
        }
    } else {
        console.warn("Container with ID \"" + containerId + "\" not found.");
    }
}

function attachToggleListeners() {
    //console.log("Attaching event listeners to toggle links.");
    var toggleLinks = document.querySelectorAll("[data-container-id][data-class]");
    //console.log("Found " + toggleLinks.length + " links.");

    // If no toggle links are found, print a warning
    if (toggleLinks.length === 0) {
        console.warn("No toggle links found on the page.");
    }
    
    for (var i = 0; i < toggleLinks.length; i++) {
        (function (toggleLink) {
            toggleLink.addEventListener("click", function (event) {
                event.preventDefault(); // Prevent default link behavior
                var containerId = toggleLink.getAttribute("data-container-id");
                var className = toggleLink.getAttribute("data-class");
                toggleVisibility(containerId, className);
            });
        })(toggleLinks[i]);
    }
}

// ===========================


$(document).ready(function () {

	// BEGIN TEXT OVERLAY CODE
	
// === TEXT OVERLAY COLOR PICKER LOGIC ===
var selectedColor = 'red';
var coloredWords = [];

document.querySelectorAll('input[name="Text Overlay[Color]"]').forEach(function (radio) {
  radio.addEventListener('change', function (e) {
    selectedColor = e.target.value;
    console.warn("Selected color:", selectedColor);
  });
});

document.querySelectorAll('span.word').forEach(function (span) {
  span.style.cursor = 'pointer';
  span.addEventListener('click', function () {
    var idMatch = span.className.match(/hover-[\w-]+/);
    if (!idMatch) return;

    var id = idMatch[0];
    var word = span.textContent;
    var glossEl = document.querySelector('.gloss.' + id);
    var gloss = glossEl ? glossEl.textContent : '';

    if (!coloredWords.some(function (w) { return w.id === id; })) {
      coloredWords.push({ id: id, hebrew: word, gloss: gloss, color: selectedColor });
    }

    span.style.backgroundColor = selectedColor;
    if (glossEl) glossEl.style.backgroundColor = selectedColor;
  });
});

window.exportAnnotations = function () {
  var output = document.getElementById('annotation-output');
  if (output) {
    output.textContent = coloredWords.map(function (w) {
      return w.id + ": " + w.hebrew + " / " + w.gloss + " [" + w.color + "]";
    }).join('\n');
  } else {
    console.warn("No #annotation-output element found.");
  }
};
	
	
	// END TEXT OVERLAY CODE


    //console.log("Document ready. Attaching event listeners to toggle links.");

    // Now attach event listeners for toggling visibility
    attachToggleListeners();

    // Wait until all Mermaid diagrams are processed
    waitForMermaidProcessing(function () {
        //console.log("Mermaid diagrams are fully processed.");

        $('div[id^="verse-"]').each(function () {
            var parentDiv = $(this);
            var svg = parentDiv.find('svg');

            if (svg.length > 0) {
                var preElement = parentDiv.find('pre.mermaid');  // The <pre> element containing the SVG
                var preWidth = preElement.width();
                var preHeight = preElement.height();
                var viewBox = svg[0].getAttribute('viewBox');

                if (viewBox) {
                    var viewBoxValues = viewBox.split(' ');
                    var viewBoxWidth = parseFloat(viewBoxValues[2]);
                    var viewBoxHeight = parseFloat(viewBoxValues[3]);
                    var scaleX = preWidth / viewBoxWidth;
                    var scaleY = preHeight / viewBoxHeight;
                    var scale = Math.min(scaleX, scaleY);

                    svg.css({
                        'width': (preWidth) + 'px',
                        'max-width': (preWidth) + 'px',
                        'height': (viewBoxHeight * scale) + 'px',
                        'position': 'relative',  // Ensure the SVG has a positioning context
                        'left': '-10px'  // Offset the SVG to the left, because firefox and others misalign it to the right. This removes the horizontal scrollbar
                    });

					// Initialize panzoom
					var panZoomInstance = Panzoom(svg[0], { 
						contain: 'outside',
						minScale: 1,  // default is 0.125
						maxScale: 10,  // default is 4
						panOnlyWhenZoomed: true //default is false
					});
                    parentDiv[0].addEventListener('wheel', panZoomInstance.zoomWithWheel);
                    parentDiv[0].addEventListener('dblclick', function (event) {
	        	    var rect = parentDiv[0].getBoundingClientRect();
				    var offsetX = event.clientX - rect.left;
				    var offsetY = event.clientY - rect.top;
				    if (event.shiftKey) {
				        // Shift + Double-click → Zoom Out
				        panZoomInstance.zoomOut({ focal: { x: offsetX, y: offsetY } });
				    } else {
				        // Regular Double-click → Zoom In
				        panZoomInstance.zoomIn({ focal: { x: offsetX, y: offsetY } });
				    }
	            });

                    // Resize handler to keep SVG scaled on window resize
                    var resizeHandler = function () {
                        var newWidth = preElement.width();

                        svg.css({
                            'width': (newWidth) + 'px',
                            'max-width': (newWidth) + 'px'
                            // Do not change the height to avoid reflowing the html page
                        });
                    };
                    
                    // Listen for resize events
                    $(window).on('resize', resizeHandler);
                }
            }
        
            
        });

        // Initially hide elements with the "highlight-phrase" class
        document.querySelectorAll(".highlight-phrase").forEach(function (element) {
            element.style.display = "none"; // Hide elements initially
        });



        // Bind lightbox functionality
        $('.lightbox-button').on('click', function () {
            // Get the target <div> ID from the button's data-target attribute
            var targetDivId = $(this).data('target'); // e.g., '#verse-1'
            var parentDiv = $(targetDivId); // Find the corresponding <div> by ID
            var associatedSvg = parentDiv.find('svg'); // Find the SVG inside the <pre>

            if (associatedSvg.length > 0) {
                openLightbox(associatedSvg[0]);
            }
        });

        // Open the lightbox and display the SVG in full-screen
        function openLightbox(svgElement) {
            // Create lightbox container if it doesn't exist            
            var lightbox = $('<div id="lightbox-overlay" class="lightbox-overlay">')
                .appendTo('body')
                .css({
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    backgroundColor: 'rgba(128, 128, 128, 0.8)',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    zIndex: 9999,
                });

            // Create the SVG container in the lightbox
                var lightboxSvgContainer = $('<div class="lightbox-svg-container">')
                .appendTo(lightbox)
                .css({
                    width: '95%',
                    height: '95%',
                    overflow: 'hidden',
                    backgroundColor: 'rgba(255, 255, 255, 1.0)',
                });

            var lightboxSvg = $(svgElement).clone().appendTo(lightboxSvgContainer);  // Clone the SVG
            // resize the svg to the available space
            lightboxSvg.css({
                'width': '100%',
                'max-width': '100%',
                'height': '100%'
            });

            // Apply panzoom to the cloned SVG in the lightbox
			var panZoomInstanceLightbox = Panzoom(lightboxSvg[0], { 
				contain: 'outside',
				minScale: 1,  // default is 0.125
				maxScale: 10,  // default is 4
				panOnlyWhenZoomed: true //default is false
			});
            lightboxSvg[0].addEventListener('wheel', panZoomInstanceLightbox.zoomWithWheel);
            lightboxSvg[0].addEventListener('dblclick', function (event) {
        	    var rect = lightboxSvg[0].getBoundingClientRect();
			    var offsetX = event.clientX - rect.left;
			    var offsetY = event.clientY - rect.top;
			    if (event.shiftKey) {
			        // Shift + Double-click → Zoom Out
			        panZoomInstanceLightbox.zoomOut({ focal: { x: offsetX, y: offsetY } });
			    } else {
			        // Regular Double-click → Zoom In
			        panZoomInstanceLightbox.zoomIn({ focal: { x: offsetX, y: offsetY } });
			    }
            });

            var closeButton = $('<button class="lightbox-close-button">Close</button>')
                .appendTo(lightbox)
                .css({
                    position: 'absolute',
                    top: '10px',
                    right: '10px',
                    backgroundColor: '#fff',
                    color: '#000',
                    border: '1px solid #bbb',
                    borderRadius: '1rem',
                    padding: '10px 20px',
                    cursor: 'pointer',
                    zIndex: 10000
                })
                .on('click', function () {
                    // Close the lightbox when the close button is clicked
                    lightbox.remove();
                });

            lightbox.on('click', function (event) {
                // Close the lightbox when clicking outside the SVG
                if ($(event.target).is(lightbox)) {
                    lightbox.remove();
                }
            });

            // Close the lightbox with the Escape key
            $(document).on('keydown', function (event) {
                if (event.key === "Escape" || event.keyCode === 27) {
                    lightbox.remove();
                    $(document).off('keydown');  // Remove the keydown listener to prevent multiple bindings
                }
            });
        }
    });

	// Bidirectional hover for Hebrew and Gloss (ES5-compatible)
	var hoverElements = document.querySelectorAll(".word, .gloss");

	// If no toggle links are found, print a warning
	    if (hoverElements.length === 0) {
	        console.warn("No hover elements found on the page.");
	    }
    	
	for (var i = 0; i < hoverElements.length; i++) {
	    (function (el) {
	        el.addEventListener("mouseenter", function () {
	            var classList = el.className.split(" ");
	            for (var j = 0; j < classList.length; j++) {
	                var cls = classList[j];
	                if (cls.indexOf("hover-") === 0) {
	                    var matches = document.getElementsByClassName(cls);
	                    for (var k = 0; k < matches.length; k++) {
	                        matches[k].classList.add("highlighted");
	                    }
	                }
	            }
	        });
	
	        el.addEventListener("mouseleave", function () {
	            var classList = el.className.split(" ");
	            for (var j = 0; j < classList.length; j++) {
	                var cls = classList[j];
	                if (cls.indexOf("hover-") === 0) {
	                    var matches = document.getElementsByClassName(cls);
	                    for (var k = 0; k < matches.length; k++) {
	                        matches[k].classList.remove("highlighted");
	                    }
	                }
	            }
	        });
	    })(hoverElements[i]);
	}
	

});