Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Common.js: Difference between revisions

MediaWiki interface page
Undo revision 205 by Eloise Zomia (talk)
Tag: Undo
No edit summary
Line 1: Line 1:
/* Landrace.wiki – Interactive map bootstrap (Common.js) */
/* Landrace.wiki – Interactive map bootstrap (FIXED VERSION) */
(function () {
(function () {
   var LVER = '1.9.4';
   var LVER = '1.9.4';
   var CDN  = 'https://unpkg.com/leaflet@' + LVER + '/dist/';
   var CDN  = 'https://unpkg.com/leaflet@' + LVER + '/dist/';


  /* --- tiny helpers to load Leaflet --- */
   function addCSS(href, id) {
   function addCSS(href, id) {
     if (id && document.getElementById(id)) return;
     if (id && document.getElementById(id)) return;
Line 11: Line 10:
     document.head.appendChild(l);
     document.head.appendChild(l);
   }
   }
 
   function addJS(src, cb) {
   function addJS(src, cb) {
     if (window.L) return cb();
     if (window.L) return cb();
     var s = document.createElement('script');
     var s = document.createElement('script');
     s.src = src; s.onload = cb;
     s.src = src;  
    s.onload = cb;
    s.onerror = function(){ console.error('Leaflet failed to load:', src); };
     document.head.appendChild(s);
     document.head.appendChild(s);
   }
   }


  /* --- UI helpers --- */
   function statusColor(s) {
   function statusColor(s) {
     return ({
     return ({
       Stable:'#2ecc71', Vulnerable:'#f1c40f',
       Stable:'#2ecc71',
       Endangered:'#e67e22', Critical:'#e74c3c', Lost:'#95a5a6'
      Vulnerable:'#f1c40f',
       Endangered:'#e67e22',
      Critical:'#e74c3c',
      Lost:'#95a5a6'
     })[s] || '#3498db';
     })[s] || '#3498db';
   }
   }
 
   function popup(kind, p) {
   function popup(kind, p) {
     if (kind === 'accessions') {
     if (kind === 'accessions') {
Line 35: Line 40:


   function initOne(el) {
   function initOne(el) {
     if (el.dataset.init) return; el.dataset.init = '1';
     if (el.dataset.init) return;  
    el.dataset.init = '1';


     var map = L.map(el).setView([20, 85], 3);
     // FIXED: Ensure height is set BEFORE map initialization
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution:'© OSM' }).addTo(map);
     if (el.clientHeight < 100) {  
 
       el.style.height = '70vh';  
     // in-map legend (matches site colors)
    var legend = L.control({ position:'bottomleft' });
    legend.onAdd = function () {
      var div = L.DomUtil.create('div', 'lw-legend-map');
      var items = [
        ['#2ecc71','Stable'], ['#f1c40f','Vulnerable'],
        ['#e67e22','Endangered'], ['#e74c3c','Critical'],
        ['#95a5a6','Lost']
      ].map(([c,l]) => `<span class=
 
/* Landrace.wiki – Interactive map bootstrap (safe hotfix) */
(function () {
  var LVER = '1.9.4';
  var CDN  = 'https://unpkg.com/leaflet@' + LVER + '/dist/';
 
  function addCSS(href, id) {
    if (id && document.getElementById(id)) return;
    var l = document.createElement('link');
    l.rel = 'stylesheet'; l.href = href; if (id) l.id = id;
    document.head.appendChild(l);
  }
  function addJS(src, cb) {
    if (window.L) return cb();
    var s = document.createElement('script');
    s.src = src; s.onload = cb; s.onerror = function(){ console.error('Leaflet failed to load:', src); };
    document.head.appendChild(s);
  }
 
  function statusColor(s) {
    return ({Stable:'#2ecc71',Vulnerable:'#f1c40f',Endangered:'#e67e22',Critical:'#e74c3c',Lost:'#95a5a6'})[s] || '#3498db';
  }
  function popup(kind, p) {
    if (kind === 'accessions') {
       var t = [p.accession_id, p.local_name].filter(Boolean).join(' — ');
      var link = p.page_url ? `<br><a href="${p.page_url}">Open accession</a>` : '';
      return `<b>${t}</b><br>${p.status||''}${link}`;
     }
     }
    return `<b>${p.name||''}</b><br>${(p.level||kind)} • ${p.status||''}`;
  }


  function initOne(el) {
     // FIXED: Always set an initial view immediately
    if (el.dataset.init) return; el.dataset.init = '1';
     var map = L.map(el).setView([20, 85], 3);
 
   
     // Ensure the map has a height even if CSS is cached/missing
     // Add the tile layer
    if (el.clientHeight < 100) { el.style.height = '70vh'; }
     L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {  
 
      attribution:'© OSM'  
     var map = L.map(el);
    }).addTo(map);
     // Defer setView until we can possibly fit to data
     L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution:'© OSM' }).addTo(map);


     // Simple legend
     // FIXED: Complete legend creation
     var legend = L.control({ position:'bottomleft' });
     var legend = L.control({ position:'bottomleft' });
     legend.onAdd = function () {
     legend.onAdd = function () {
Line 96: Line 62:
       div.innerHTML = [
       div.innerHTML = [
         ['#2ecc71','Stable'], ['#f1c40f','Vulnerable'],
         ['#2ecc71','Stable'], ['#f1c40f','Vulnerable'],
         ['#e67e22','Endangered'], ['#e74c3c','Critical'], ['#95a5a6','Lost']
         ['#e67e22','Endangered'], ['#e74c3c','Critical'],  
        ['#95a5a6','Lost']
       ].map(([c,l]) => `<span class="item"><span class="dot" style="background:${c}"></span>${l}</span>`).join('');
       ].map(([c,l]) => `<span class="item"><span class="dot" style="background:${c}"></span>${l}</span>`).join('');
       return div;
       return div;
Line 109: Line 76:


     var layers = [];
     var layers = [];
    var dataLoadCount = 0;
    var expectedDataSources = 0;
   
    // Count expected data sources
    ['regions','populations','accessions'].forEach(function(kind) {
      if (el.dataset[kind]) expectedDataSources++;
    });
     function maybeFit() {
     function maybeFit() {
       try {
       try {
         var group = L.featureGroup(layers);
         if (layers.length > 0) {
        var b = group.getBounds();
          var group = L.featureGroup(layers);
        if (b && b.isValid()) {
          var b = group.getBounds();
          map.fitBounds(b.pad(0.15));
          if (b && b.isValid()) {
        } else {
            map.fitBounds(b.pad(0.15));
           // Fallback view (India/SEA)
            return;
          map.setView([20, 85], 4);
           }
         }
         }
        // Fallback view if no valid bounds
        map.setView([20, 85], 3);
       } catch (e) {
       } catch (e) {
         map.setView([20, 85], 4);
        console.error('Map fitting error:', e);
         map.setView([20, 85], 3);
       }
       }
       // Make sure Leaflet recalculates size once container CSS is applied
     
       setTimeout(function(){ map.invalidateSize(true); }, 0);
       // FIXED: Always invalidate size after view changes
       setTimeout(function(){  
        map.invalidateSize(true);  
      }, 100);
     }
     }


     var hadAnyData = false;
     // Load data sources
     ['regions','populations','accessions'].forEach(function (kind) {
     ['regions','populations','accessions'].forEach(function (kind) {
       var url = el.dataset[kind];
       var url = el.dataset[kind];
       if (!url) return;
       if (!url) return;
     
      console.log('Loading', kind, 'from', url); // Debug logging
     
       fetch(url).then(function(r){
       fetch(url).then(function(r){
         if (!r.ok) throw new Error(kind + ' fetch ' + r.status + ' ' + url);
         if (!r.ok) throw new Error(kind + ' fetch ' + r.status + ' ' + url);
         return r.json();
         return r.json();
       }).then(function (g) {
       }).then(function (g) {
         hadAnyData = true;
         console.log('Loaded', kind, '- features:', g.features ? g.features.length : 'unknown'); // Debug logging
       
         var layer = L.geoJSON(g, Object.assign({
         var layer = L.geoJSON(g, Object.assign({
           onEachFeature: (f, ly) => {
           onEachFeature: (f, ly) => {
Line 143: Line 128:
           }
           }
         }, cfg[kind])).addTo(map);
         }, cfg[kind])).addTo(map);
       
         layers.push(layer);
         layers.push(layer);
        dataLoadCount++;
       
        // FIXED: Only fit bounds after all expected data is loaded
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
       }).catch(function(err){
       }).catch(function(err){
         console.error('[Landrace.wiki map]', err);
         console.error('[Landrace.wiki map]', kind, err);
      }).finally(function(){
        dataLoadCount++;
         // Fit after each dataset tries, but only once
       
         if (!el.dataset.fitted) {
         // Still try to fit even if some data failed
          el.dataset.fitted = '1';
         if (dataLoadCount >= expectedDataSources) {
           maybeFit();
           maybeFit();
         }
         }
Line 155: Line 147:
     });
     });


     // If no data-* URLs at all, still set a sane view
     // FIXED: If no data sources, immediately set view and invalidate size
     if (!el.dataset.regions && !el.dataset.populations && !el.dataset.accessions) {
     if (expectedDataSources === 0) {
       map.setView([20, 85], 4);
      console.log('No data sources found, using default view');
       setTimeout(function(){ map.invalidateSize(true); }, 0);
       map.setView([20, 85], 3);
       setTimeout(function(){  
        map.invalidateSize(true);  
      }, 100);
     }
     }
   }
   }
Line 166: Line 161:
   }
   }


  // Load Leaflet and initialize
   addCSS(CDN + 'leaflet.css', 'leaflet-css');
   addCSS(CDN + 'leaflet.css', 'leaflet-css');
   addJS(CDN + 'leaflet.js', function () {
   addJS(CDN + 'leaflet.js', function () {
    console.log('Leaflet loaded, initializing maps...');
     init();
     init();
     if (window.mw && mw.hook) mw.hook('wikipage.content').add(function ($c) { init($c && $c[0] ? $c[0] : document); });
   
    // MediaWiki integration
     if (window.mw && mw.hook) {
      mw.hook('wikipage.content').add(function ($c) {  
        init($c && $c[0] ? $c[0] : document);  
      });
    }
   });
   });
})();
})();

Revision as of 08:52, 24 August 2025

/* Landrace.wiki – Interactive map bootstrap (FIXED VERSION) */
(function () {
  var LVER = '1.9.4';
  var CDN  = 'https://unpkg.com/leaflet@' + LVER + '/dist/';

  function addCSS(href, id) {
    if (id && document.getElementById(id)) return;
    var l = document.createElement('link');
    l.rel = 'stylesheet'; l.href = href; if (id) l.id = id;
    document.head.appendChild(l);
  }
  
  function addJS(src, cb) {
    if (window.L) return cb();
    var s = document.createElement('script');
    s.src = src; 
    s.onload = cb; 
    s.onerror = function(){ console.error('Leaflet failed to load:', src); };
    document.head.appendChild(s);
  }

  function statusColor(s) {
    return ({
      Stable:'#2ecc71',
      Vulnerable:'#f1c40f',
      Endangered:'#e67e22',
      Critical:'#e74c3c',
      Lost:'#95a5a6'
    })[s] || '#3498db';
  }
  
  function popup(kind, p) {
    if (kind === 'accessions') {
      var t = [p.accession_id, p.local_name].filter(Boolean).join(' — ');
      var link = p.page_url ? `<br><a href="${p.page_url}">Open accession</a>` : '';
      return `<b>${t}</b><br>${p.status||''}${link}`;
    }
    return `<b>${p.name||''}</b><br>${(p.level||kind)} • ${p.status||''}`;
  }

  function initOne(el) {
    if (el.dataset.init) return; 
    el.dataset.init = '1';

    // FIXED: Ensure height is set BEFORE map initialization
    if (el.clientHeight < 100) { 
      el.style.height = '70vh'; 
    }

    // FIXED: Always set an initial view immediately
    var map = L.map(el).setView([20, 85], 3);
    
    // Add the tile layer
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { 
      attribution:'© OSM' 
    }).addTo(map);

    // FIXED: Complete legend creation
    var legend = L.control({ position:'bottomleft' });
    legend.onAdd = function () {
      var div = L.DomUtil.create('div', 'lw-legend-map');
      div.innerHTML = [
        ['#2ecc71','Stable'], ['#f1c40f','Vulnerable'],
        ['#e67e22','Endangered'], ['#e74c3c','Critical'], 
        ['#95a5a6','Lost']
      ].map(([c,l]) => `<span class="item"><span class="dot" style="background:${c}"></span>${l}</span>`).join('');
      return div;
    };
    legend.addTo(map);

    var cfg = {
      regions:     { style: f => ({ color: statusColor(f.properties.status), weight: 1, fillOpacity: 0.15 }) },
      populations: { pointToLayer: (f, ll) => L.circleMarker(ll, { radius: 5, color: statusColor(f.properties.status) }) },
      accessions:  { pointToLayer: (f, ll) => L.circleMarker(ll, { radius: 4, color: statusColor(f.properties.status) }) }
    };

    var layers = [];
    var dataLoadCount = 0;
    var expectedDataSources = 0;
    
    // Count expected data sources
    ['regions','populations','accessions'].forEach(function(kind) {
      if (el.dataset[kind]) expectedDataSources++;
    });

    function maybeFit() {
      try {
        if (layers.length > 0) {
          var group = L.featureGroup(layers);
          var b = group.getBounds();
          if (b && b.isValid()) {
            map.fitBounds(b.pad(0.15));
            return;
          }
        }
        // Fallback view if no valid bounds
        map.setView([20, 85], 3);
      } catch (e) {
        console.error('Map fitting error:', e);
        map.setView([20, 85], 3);
      }
      
      // FIXED: Always invalidate size after view changes
      setTimeout(function(){ 
        map.invalidateSize(true); 
      }, 100);
    }

    // Load data sources
    ['regions','populations','accessions'].forEach(function (kind) {
      var url = el.dataset[kind];
      if (!url) return;
      
      console.log('Loading', kind, 'from', url); // Debug logging
      
      fetch(url).then(function(r){
        if (!r.ok) throw new Error(kind + ' fetch ' + r.status + ' ' + url);
        return r.json();
      }).then(function (g) {
        console.log('Loaded', kind, '- features:', g.features ? g.features.length : 'unknown'); // Debug logging
        
        var layer = L.geoJSON(g, Object.assign({
          onEachFeature: (f, ly) => {
            var p = f.properties || {};
            ly.bindPopup(popup(kind, p));
            var title = p.accession_id || p.name || '';
            if (title) ly.bindTooltip(title, { direction:'top', offset:[0,-4], opacity:0.9 });
          }
        }, cfg[kind])).addTo(map);
        
        layers.push(layer);
        dataLoadCount++;
        
        // FIXED: Only fit bounds after all expected data is loaded
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
      }).catch(function(err){
        console.error('[Landrace.wiki map]', kind, err);
        dataLoadCount++;
        
        // Still try to fit even if some data failed
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
      });
    });

    // FIXED: If no data sources, immediately set view and invalidate size
    if (expectedDataSources === 0) {
      console.log('No data sources found, using default view');
      map.setView([20, 85], 3);
      setTimeout(function(){ 
        map.invalidateSize(true); 
      }, 100);
    }
  }

  function init(root) {
    (root || document).querySelectorAll('.lw-map').forEach(initOne);
  }

  // Load Leaflet and initialize
  addCSS(CDN + 'leaflet.css', 'leaflet-css');
  addJS(CDN + 'leaflet.js', function () {
    console.log('Leaflet loaded, initializing maps...');
    init();
    
    // MediaWiki integration
    if (window.mw && mw.hook) {
      mw.hook('wikipage.content').add(function ($c) { 
        init($c && $c[0] ? $c[0] : document); 
      });
    }
  });
})();