Lompat ke isi

MediaWiki:Common.js: Perbedaan antara revisi

Dari Mippedia Data, basis data terbuka
Tidak ada ringkasan suntingan
Tanda: Suntingan perangkat seluler Suntingan peramban seluler
Tidak ada ringkasan suntingan
Tanda: Dikembalikan Suntingan perangkat seluler Suntingan peramban seluler
Baris 1: Baris 1:
/* ==========================================================
/* ==========================================================
   🧠 MIPPEDIA DATA - SMART CONTEXT + AUTO THUMBNAIL
   🧠 MIPPEDIA DATA - SMART CONTEXT + AUTO THUMB & DESC
   Features: Smart Sync, Auto-Age, Auto-Bold, Smart Links,
   Features: Smart Sync, Auto-Age, Auto-Bold, Smart Links,
             Dynamic Context, AND NEW: Auto Thumbnail Image
             Dynamic Context, Auto Thumbnail, AND Image Caption
   ========================================================== */
   ========================================================== */
(function() {
(function() {
Baris 13: Baris 13:


         var pageTitle = mw.config.get('wgPageName').replace(/_/g, ' '),
         var pageTitle = mw.config.get('wgPageName').replace(/_/g, ' '),
             cacheKey = 'mip_smart_context_thumb_' + pageTitle, now = new Date().getTime(),
             cacheKey = 'mip_v5_full_' + pageTitle, now = new Date().getTime(),
             currentYear = 2026;
             currentYear = 2026;


Baris 22: Baris 22:
         ];
         ];


         // --- SEMUA FUNGSI AWAL (TETAP UTUH) ---
         // --- SEMUA FUNGSI AWAL (TETAP UTUH 100%) ---
         function applyAutoBold(text) { return text.replace(new RegExp('(' + pageTitle + ')', 'gi'), '<strong>$1</strong>'); }
         function applyAutoBold(text) { return text.replace(new RegExp('(' + pageTitle + ')', 'gi'), '<strong>$1</strong>'); }
         function cleanExtract(text) { return text.replace(/\[\d+\]/g, '').replace(/\{\{[^}]+\}\}/g, '').replace(/\(\s*\)/g, '').replace(/\s\s+/g, ' ').trim(); }
         function cleanExtract(text) { return text.replace(/\[\d+\]/g, '').replace(/\{\{[^}]+\}\}/g, '').replace(/\(\s*\)/g, '').replace(/\s\s+/g, ' ').trim(); }
Baris 62: Baris 62:
         }
         }


         // --- SISTEM SMART CHECK DENGAN SUPPORT THUMBNAIL ---
         // --- SISTEM SMART CHECK (CEK TIMESTAMP & GAMBAR & CAPTION) ---
         var cached = JSON.parse(localStorage.getItem(cacheKey) || "{}");
         var cached = JSON.parse(localStorage.getItem(cacheKey) || "{}");


Baris 69: Baris 69:
             $.ajax({
             $.ajax({
                 url: pCheck.url,
                 url: pCheck.url,
                 data: { action: 'query', prop: 'revisions|pageimages', rvprop: 'timestamp', piprop: 'thumbnail', pithumbsize: 150, titles: pageTitle, format: 'json', origin: '*' },
                // Ditambahkan pengambilan 'pageterms' untuk nyari deskripsi gambar otomatis
                 data: { action: 'query', prop: 'revisions|pageimages|pageterms', rvprop: 'timestamp', piprop: 'thumbnail', pithumbsize: 200, titles: pageTitle, format: 'json', origin: '*' },
                 dataType: 'json',
                 dataType: 'json',
                 success: function(res) {
                 success: function(res) {
                     var pg = res.query.pages, id = Object.keys(pg)[0];
                     var pg = res.query.pages, id = Object.keys(pg)[0];
                     var latestTS = (id != "-1") ? pg[id].revisions[0].timestamp : "0";
                     var latestTS = (id != "-1") ? pg[id].revisions[0].timestamp : "0";
                    // Ambil thumbnail kalau ada
                     var thumbUrl = (id != "-1" && pg[id].thumbnail) ? pg[id].thumbnail.source : "";
                     var thumbUrl = (id != "-1" && pg[id].thumbnail) ? pg[id].thumbnail.source : "";
                   
                    // Coba ambil deskripsi gambar (caption) dari metadata kalau ada
                    var caption = "";
                    if (id != "-1" && pg[id].terms && pg[id].terms.label) {
                        caption = pg[id].terms.label[0];
                    }


                     if (cached.content && cached.ts === latestTS) {
                     if (cached.content && cached.ts === latestTS) {
                         renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img);
                         renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img, cached.cap);
                     } else {  
                     } else { fetchFreshData(latestTS, thumbUrl, caption); }
                        fetchFreshData(latestTS, thumbUrl);  
                    }
                 },
                 },
                 error: function() { if (cached.content) renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img); }
                 error: function() { if (cached.content) renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img, cached.cap); }
             });
             });
         }
         }


         function fetchFreshData(newTS, img) {
         function fetchFreshData(newTS, img, cap) {
             var found = false;
             var found = false, shuffled = projects.sort(() => Math.random() - 0.5);
            var shuffled = projects.sort(() => Math.random() - 0.5);
             shuffled.forEach(function(p) {
             shuffled.forEach(function(p) {
                 if (found) return;
                 if (found) return;
Baris 105: Baris 108:
                                 $.ajax({ url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=id&dt=t&q=" + encodeURIComponent(extract), success: function(res) {  
                                 $.ajax({ url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=id&dt=t&q=" + encodeURIComponent(extract), success: function(res) {  
                                     var trans = ""; res[0].forEach(s => { if (s[0]) trans += s[0]; });
                                     var trans = ""; res[0].forEach(s => { if (s[0]) trans += s[0]; });
                                     finalize(p, trans, true, extract, newTS, img);
                                     finalize(p, trans, true, extract, newTS, img, cap);
                                 }});
                                 }});
                             } else {  
                             } else { finalize(p, extract, false, "", newTS, img, cap); }
                                finalize(p, extract, false, "", newTS, img);  
                            }
                         }
                         }
                     }
                     }
Baris 116: Baris 117:
         }
         }


         function finalize(p, c, t, o, ts, img) {
         function finalize(p, c, t, o, ts, img, cap) {
             localStorage.setItem(cacheKey, JSON.stringify({p:p, content:c, isTrans:t, orig:o, ts:ts, img:img}));
             localStorage.setItem(cacheKey, JSON.stringify({p:p, content:c, isTrans:t, orig:o, ts:ts, img:img, cap:cap}));
             renderAll(p, c, t, o, img);
             renderAll(p, c, t, o, img, cap);
         }
         }


         function renderAll(p, currentText, isTranslated, originalText, img) {
         function renderAll(p, currentText, isTranslated, originalText, img, cap) {
             var processedText = applyAutoBold(applyDynamicContext(currentText));
             var processedText = applyAutoBold(applyDynamicContext(currentText));
            $descSection.show();
              
              
             // Layouting Thumbnail (Tetap ringan: hanya render jika gambar ada)
             // --- RENDER THUMBNAIL + CAPTION ---
             var thumbHtml = img ? '<div style="float: right; margin-left: 15px; margin-bottom: 10px; border: 1px solid #ddd; padding: 3px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><img src="'+img+'" style="max-width: 100px; display: block; height: auto;"></div>' : '';
             var thumbHtml = "";
            if (img) {
                thumbHtml = '<div style="float: right; margin-left: 15px; margin-bottom: 10px; border: 1px solid #ddd; padding: 3px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 110px; text-align: center;">' +
                            '<img src="'+img+'" style="width: 100%; height: auto; display: block; border-radius: 2px;">';
                // Jika caption ada, tampilkan di bawah gambar
                if (cap) {
                    thumbHtml += '<div style="font-size: 10px; color: #555; margin-top: 5px; line-height: 1.2; padding: 0 2px; font-style: italic;">' + cap + '</div>';
                }
                thumbHtml += '</div>';
            }


            $descSection.show();
            // Masukkan thumbnail ke dalam konten box
             $descBox.show().html(thumbHtml + applySummary(processedText) + '<div style="clear:both;"></div>');
             $descBox.show().html(thumbHtml + applySummary(processedText) + '<div style="clear:both;"></div>');
              
              
Baris 142: Baris 151:
                 var isOrig = ($(this).text() === 'Tampilkan versi asli');
                 var isOrig = ($(this).text() === 'Tampilkan versi asli');
                 var textToDisplay = applyAutoBold(applyDynamicContext(isOrig ? originalText : currentText));
                 var textToDisplay = applyAutoBold(applyDynamicContext(isOrig ? originalText : currentText));
                // Pastikan thumbnail tetap ada saat toggle versi asli
                 $descBox.html(thumbHtml + applySummary(textToDisplay) + '<div style="clear:both;"></div>');
                 $descBox.html(thumbHtml + applySummary(textToDisplay) + '<div style="clear:both;"></div>');
                 $(this).text(isOrig ? 'Tampilkan terjemahan' : 'Tampilkan versi asli');
                 $(this).text(isOrig ? 'Tampilkan terjemahan' : 'Tampilkan versi asli');

Revisi per 16 April 2026 09.15

/* ==========================================================
   🧠 MIPPEDIA DATA - SMART CONTEXT + AUTO THUMB & DESC
   Features: Smart Sync, Auto-Age, Auto-Bold, Smart Links,
             Dynamic Context, Auto Thumbnail, AND Image Caption
   ========================================================== */
(function() {
    $(document).ready(function() {
        var $descSection = $('#mip-desc-section'), $descBox = $('#mip-auto-description'),
            $sourceInfo = $('#mip-source-info'), $portalLinks = $('#mip-portal-links'),
            $projectPortal = $('#mip-project-portal');
        
        if (!$descBox.length) return;

        var pageTitle = mw.config.get('wgPageName').replace(/_/g, ' '),
            cacheKey = 'mip_v5_full_' + pageTitle, now = new Date().getTime(),
            currentYear = 2026;

        var projects = [
            { id: 'id', name: 'Mippedia bahasa Indonesia', url: 'https://id.mippedia.org/api.php', base: 'https://id.mippedia.org/wiki/', label: 'Bahasa Indonesia' },
            { id: 'en', name: 'Mippedia bahasa Inggris', url: 'https://en.mippedia.org/api.php', base: 'https://en.mippedia.org/wiki/', label: 'Bahasa Inggris' },
            { id: 'concise', name: 'Mippedia bahasa Indonesia ringkas', url: 'https://concise.mippedia.org/api.php', base: 'https://concise.mippedia.org/wiki/', label: 'Versi Ringkas' }
        ];

        // --- SEMUA FUNGSI AWAL (TETAP UTUH 100%) ---
        function applyAutoBold(text) { return text.replace(new RegExp('(' + pageTitle + ')', 'gi'), '<strong>$1</strong>'); }
        function cleanExtract(text) { return text.replace(/\[\d+\]/g, '').replace(/\{\{[^}]+\}\}/g, '').replace(/\(\s*\)/g, '').replace(/\s\s+/g, ' ').trim(); }
        
        function applyDynamicContext(text) {
            var date = new Date();
            var hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];
            var bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
            var tglSkrg = hari[date.getDay()] + ", " + date.getDate() + " " + bulan[date.getMonth()] + " " + date.getFullYear();

            return text
                .replace(/(hari ini|saat ini|sekarang)/gi, '$1 (' + tglSkrg + ')')
                .replace(/(\d{1,2}\s(?:Januari|Februari|Maret|April|Mei|Juni|Juli|Agustus|September|Oktober|November|Desember)\s(\d{4}))/gi, function(m, f, y) { 
                    return f + " <span style='color: #444; font-weight: bold;'>– usia " + (currentYear - parseInt(y)) + " tahun</span>"; 
                })
                .replace(/(sejak|tahun)\s(\d{4})/gi, function(m, k, y) {
                    var gap = currentYear - parseInt(y);
                    if (gap > 0 && gap < 100) return k + " " + y + " <small style='color: #888;'>(" + gap + " thn lalu)</small>";
                    return m;
                });
        }

        function applySummary(text) {
            var limit = 250;
            if (text.length <= limit) return '<span>' + text + '</span>';
            return '<span>' + text.substring(0, limit) + '</span><span class="mip-dots">... </span><span class="mip-more" style="display:none;">' + text.substring(limit) + '</span><span class="mip-read-btn" style="color: #6a5acd; cursor: pointer; font-weight: bold; margin-left: 5px;">Baca selengkapnya</span>';
        }

        function buildSmartLinks(currentId) {
            $portalLinks.empty();
            var validLinks = [];
            var checkRequests = projects.filter(p => p.id !== currentId).map(function(p) {
                return $.ajax({ url: p.url, data: { action: 'query', titles: pageTitle, format: 'json', origin: '*' }, dataType: 'json' })
                    .then(function(data) { if (data.query.pages["-1"] === undefined) { validLinks.push('<a href="' + p.base + encodeURIComponent(pageTitle) + '" target="_blank" style="color: #6a5acd; text-decoration: underline; font-weight: bold;">' + p.label + '</a>'); } });
            });
            $.when.apply($, checkRequests).done(function() {
                if (validLinks.length > 0) { $portalLinks.html(validLinks.join(' <span style="color:#ccc; margin: 0 5px;">•</span> ')); $projectPortal.fadeIn(); }
            });
        }

        // --- SISTEM SMART CHECK (CEK TIMESTAMP & GAMBAR & CAPTION) ---
        var cached = JSON.parse(localStorage.getItem(cacheKey) || "{}");

        function init() {
            var pCheck = projects[Math.floor(Math.random() * projects.length)];
            $.ajax({
                url: pCheck.url,
                // Ditambahkan pengambilan 'pageterms' untuk nyari deskripsi gambar otomatis
                data: { action: 'query', prop: 'revisions|pageimages|pageterms', rvprop: 'timestamp', piprop: 'thumbnail', pithumbsize: 200, titles: pageTitle, format: 'json', origin: '*' },
                dataType: 'json',
                success: function(res) {
                    var pg = res.query.pages, id = Object.keys(pg)[0];
                    var latestTS = (id != "-1") ? pg[id].revisions[0].timestamp : "0";
                    var thumbUrl = (id != "-1" && pg[id].thumbnail) ? pg[id].thumbnail.source : "";
                    
                    // Coba ambil deskripsi gambar (caption) dari metadata kalau ada
                    var caption = "";
                    if (id != "-1" && pg[id].terms && pg[id].terms.label) {
                        caption = pg[id].terms.label[0]; 
                    }

                    if (cached.content && cached.ts === latestTS) {
                        renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img, cached.cap);
                    } else { fetchFreshData(latestTS, thumbUrl, caption); }
                },
                error: function() { if (cached.content) renderAll(cached.p, cached.content, cached.isTrans, cached.orig, cached.img, cached.cap); }
            });
        }

        function fetchFreshData(newTS, img, cap) {
            var found = false, shuffled = projects.sort(() => Math.random() - 0.5);
            shuffled.forEach(function(p) {
                if (found) return;
                $.ajax({
                    url: p.url,
                    data: { action: 'query', prop: 'extracts', exintro: 1, explaintext: 1, titles: pageTitle, format: 'json', origin: '*' },
                    dataType: 'json',
                    success: function(data) {
                        if (found) return;
                        var pages = data.query.pages, pageId = Object.keys(pages)[0];
                        if (pageId != "-1" && pages[pageId].extract) {
                            found = true;
                            var extract = cleanExtract(pages[pageId].extract);
                            if (p.id === 'en') {
                                $.ajax({ url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=id&dt=t&q=" + encodeURIComponent(extract), success: function(res) { 
                                    var trans = ""; res[0].forEach(s => { if (s[0]) trans += s[0]; });
                                    finalize(p, trans, true, extract, newTS, img, cap);
                                }});
                            } else { finalize(p, extract, false, "", newTS, img, cap); }
                        }
                    }
                });
            });
        }

        function finalize(p, c, t, o, ts, img, cap) {
            localStorage.setItem(cacheKey, JSON.stringify({p:p, content:c, isTrans:t, orig:o, ts:ts, img:img, cap:cap}));
            renderAll(p, c, t, o, img, cap);
        }

        function renderAll(p, currentText, isTranslated, originalText, img, cap) {
            var processedText = applyAutoBold(applyDynamicContext(currentText));
            $descSection.show();
            
            // --- RENDER THUMBNAIL + CAPTION ---
            var thumbHtml = "";
            if (img) {
                thumbHtml = '<div style="float: right; margin-left: 15px; margin-bottom: 10px; border: 1px solid #ddd; padding: 3px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); width: 110px; text-align: center;">' +
                            '<img src="'+img+'" style="width: 100%; height: auto; display: block; border-radius: 2px;">';
                // Jika caption ada, tampilkan di bawah gambar
                if (cap) {
                    thumbHtml += '<div style="font-size: 10px; color: #555; margin-top: 5px; line-height: 1.2; padding: 0 2px; font-style: italic;">' + cap + '</div>';
                }
                thumbHtml += '</div>';
            }

            $descBox.show().html(thumbHtml + applySummary(processedText) + '<div style="clear:both;"></div>');
            
            var footer = '<div style="font-size: 0.9em; color: #777;">Sumber Dari : <a href="' + p.base + encodeURIComponent(pageTitle) + '" target="_blank" style="color: #6a5acd; font-weight: bold; text-decoration: none;">' + p.name + '.</a>';
            if (isTranslated) { footer += '<br><span style="font-size: 0.85em; font-style: italic;">(Diterjemahkan secara otomatis)</span> <span id="mip-toggle-orig" style="color: #6a5acd; cursor: pointer; text-decoration: underline; margin-left: 5px;">Tampilkan versi asli</span>'; }
            $sourceInfo.show().html(footer);
            
            buildSmartLinks(p.id);
            
            // Handlers
            $(document).off('click', '.mip-read-btn').on('click', '.mip-read-btn', function() { $(this).hide(); $('.mip-dots').hide(); $('.mip-more').fadeIn(); });
            $(document).off('click', '#mip-toggle-orig').on('click', '#mip-toggle-orig', function() {
                var isOrig = ($(this).text() === 'Tampilkan versi asli');
                var textToDisplay = applyAutoBold(applyDynamicContext(isOrig ? originalText : currentText));
                $descBox.html(thumbHtml + applySummary(textToDisplay) + '<div style="clear:both;"></div>');
                $(this).text(isOrig ? 'Tampilkan terjemahan' : 'Tampilkan versi asli');
            });
        }

        init();
    });
})();