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
No edit summary
Tag: Reverted
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* Landrace.wiki – Interactive map bootstrap (single, fixed block) */
/* Landrace.wiki – Simple fixed map (MediaWiki compatible) */
(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/';


  console.log('[Landrace] Common.js boot');
  /* --- load Leaflet --- */
   function addCSS(href, id) {
   function addCSS(href, id) {
     if (id && document.getElementById(id)) return;
     if (id && document.getElementById(id)) return;
Line 13: 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.onerror = function(){ console.error('[Landrace] Leaflet failed:', 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') {
       var t = [p.accession_id, p.local_name].filter(Boolean).join(' — ');
       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>' : '';
       var link = p.page_url ? `<br><a href="${p.page_url}">Open accession</a>` : '';
       return '<b>'+t+'</b><br>'+(p.status||'')+link;
       return `<b>${t}</b><br>${p.status||''}${link}`;
     }
     }
     return '<b>'+(p.name||'')+'</b><br>'+((p.level||kind)+' '+(p.status||''));
     return `<b>${p.name||''}</b><br>${(p.level||kind)} ${p.status||''}`;
   }
   }


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


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


     var map = L.map(el);
    // FIXED: Set zoom limits directly in map options
     L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution:'© OSM' }).addTo(map);
     var map = L.map(el, {
      minZoom: 2,      // Can't zoom out past world view
      maxZoom: 15,    // Reasonable max zoom for this type of data
      zoomControl: true
    }).setView([15, 105], 5); // Better initial view for Southeast Asia
   
    // Add the tile layer
     L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {  
      attribution:'© OSM'  
    }).addTo(map);


     // Legend
     // SIMPLE legend that works with MediaWiki CSS
     var legend = L.control({ position:'bottomleft' });
     var legend = L.control({ position:'bottomleft' });
     legend.onAdd = function () {
     legend.onAdd = function () {
       var div = L.DomUtil.create('div', 'lw-legend-map');
       var div = L.DomUtil.create('div', 'lw-legend-map');
     
      // Use inline styles to avoid CSS conflicts
      div.style.cssText = `
        background: white;
        padding: 12px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        border: 1px solid #ccc;
        font-size: 12px;
        line-height: 1.4;
      `;
     
      var html = '<div style="font-weight: bold; margin-bottom: 8px; color: #333;">Conservation Status</div>';
     
       var items = [
       var items = [
         ['#2ecc71','Stable'],
         ['#2ecc71', 'Stable'],
         ['#f1c40f','Vulnerable'],
         ['#f1c40f', 'Vulnerable'],  
         ['#e67e22','Endangered'],
         ['#e67e22', 'Endangered'],
         ['#e74c3c','Critical'],
         ['#e74c3c', 'Critical'],
         ['#95a5a6','Lost']
         ['#95a5a6', 'Lost']
       ].map(function (x) {
       ];
         var c = x[0], l = x[1];
     
        return '<span class="item"><span class="dot" style="background:'+c+'"></span>'+l+'</span>';
      items.forEach(function([color, label]) {
       }).join('');
         html += `
       div.innerHTML = items;
          <div style="display: flex; align-items: center; margin: 6px 0;">
            <div style="
              width: 12px;
              height: 12px;
              background: ${color};
              border-radius: 50%;
              margin-right: 8px;
              border: 1px solid rgba(0,0,0,0.2);
            "></div>
            <span style="color: #555;">${label}</span>
          </div>
        `;
       });
     
       div.innerHTML = html;
       return div;
       return div;
     };
     };
Line 66: Line 108:


     var cfg = {
     var cfg = {
       regions:    { style: function (f) { return { color: statusColor(f.properties.status), weight: 1, fillOpacity: 0.15 }; } },
       regions:    {  
       populations: { pointToLayer: function (f, ll) { return L.circleMarker(ll, { radius: 5, color: statusColor(f.properties.status) }); } },
        style: f => ({  
       accessions:  { pointToLayer: function (f, ll) { return L.circleMarker(ll, { radius: 4, color: statusColor(f.properties.status) }); } }
          color: statusColor(f.properties.status),  
          weight: 2,  
          fillOpacity: 0.2,
          opacity: 0.8
        })
      },
       populations: {  
        pointToLayer: (f, ll) => L.circleMarker(ll, {  
          radius: 6,  
          color: '#fff',
          weight: 2,
          fillColor: statusColor(f.properties.status),
          fillOpacity: 0.8
        })
      },
       accessions:  {  
        pointToLayer: (f, ll) => L.circleMarker(ll, {  
          radius: 5,  
          color: '#fff',
          weight: 2,
          fillColor: statusColor(f.properties.status),
          fillOpacity: 0.9
        })
      }
     };
     };


     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), b = group.getBounds();
         if (layers.length > 0) {
        if (b && b.isValid()) { map.fitBounds(b.pad(0.15)); }
          var group = L.featureGroup(layers);
         else { map.setView([20, 85], 4); }
          var b = group.getBounds();
       } catch (e) { map.setView([20, 85], 4); }
          if (b && b.isValid()) {
       setTimeout(function(){ map.invalidateSize(true); }, 0);
            // Fit bounds but respect zoom limits
            map.fitBounds(b.pad(0.2), {
              maxZoom: 10  // Don't zoom in too much when auto-fitting
            });
            return;
          }
        }
         // Fallback view
        map.setView([15, 105], 5);
       } catch (e) {
        console.error('Map fitting error:', e);
        map.setView([15, 105], 5);
      }
     
       setTimeout(function(){  
        map.invalidateSize(true);  
      }, 100);
     }
     }


    // 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);
     
       fetch(url).then(function(r){
       fetch(url).then(function(r){
         if (!r.ok) throw new Error(kind+' '+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) {
        console.log('Loaded', kind, '- features:', g.features ? g.features.length : 'unknown');
       
         var layer = L.geoJSON(g, Object.assign({
         var layer = L.geoJSON(g, Object.assign({
           onEachFeature: function (f, ly) {
           onEachFeature: (f, ly) => {
             var p = f.properties || {};
             var p = f.properties || {};
             ly.bindPopup(popup(kind, p));
             ly.bindPopup(popup(kind, p));
             var title = p.accession_id || p.name || '';
             var title = p.accession_id || p.name || '';
             if (title) ly.bindTooltip(title, { direction:'top', offset:[0,-4], opacity:0.9 });
             if (title) ly.bindTooltip(title, { direction:'top', offset:[0,-8], opacity:0.9 });
           }
           }
         }, cfg[kind])).addTo(map);
         }, cfg[kind])).addTo(map);
       
         layers.push(layer);
         layers.push(layer);
        dataLoadCount++;
       
        // Only fit bounds after all expected data is loaded
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
       }).catch(function(err){
       }).catch(function(err){
         console.error('[Landrace map]', err);
         console.error('[Landrace.wiki map]', kind, err);
      }).finally(function(){
        dataLoadCount++;
         if (!el.dataset.fitted) { el.dataset.fitted = '1'; maybeFit(); }
       
         if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
       });
       });
     });
     });


     if (!el.dataset.regions && !el.dataset.populations && !el.dataset.accessions) {
    // If no data sources, immediately set view
       map.setView([20, 85], 4);
     if (expectedDataSources === 0) {
       setTimeout(function(){ map.invalidateSize(true); }, 0);
      console.log('No data sources found, using default view');
       map.setView([15, 105], 5);
       setTimeout(function(){  
        map.invalidateSize(true);  
      }, 100);
     }
     }
    // Add a simple zoom level indicator in the corner
    var zoomDisplay = L.control({ position: 'topright' });
    zoomDisplay.onAdd = function() {
      var div = L.DomUtil.create('div');
      div.style.cssText = `
        background: rgba(255,255,255,0.9);
        padding: 5px 8px;
        border-radius: 4px;
        font-size: 11px;
        color: #666;
        border: 1px solid #ccc;
      `;
      div.innerHTML = 'Zoom: ' + map.getZoom();
     
      map.on('zoomend', function() {
        div.innerHTML = 'Zoom: ' + map.getZoom() + ' (min: 2, max: 15)';
      });
     
      return div;
    };
    zoomDisplay.addTo(map);
   }
   }


   function init(root) {
   function init(root) {
     var nodes = (root || document).querySelectorAll('.lw-map');
     (root || document).querySelectorAll('.lw-map').forEach(initOne);
    console.log('[Landrace] .lw-map containers:', nodes.length);
    Array.prototype.forEach.call(nodes, initOne);
   }
   }


  // 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('[Landrace] Leaflet ready:', !!window.L);
     console.log('Leaflet loaded, initializing maps...');
     init();
     init();
   
    // MediaWiki integration
     if (window.mw && mw.hook) {
     if (window.mw && mw.hook) {
       mw.hook('wikipage.content').add(function ($c) {
       mw.hook('wikipage.content').add(function ($c) {  
         init($c && $c[0] ? $c[0] : document);
         init($c && $c[0] ? $c[0] : document);  
       });
       });
     }
     }
   });
   });
})();
})();

Latest revision as of 11:49, 24 August 2025

/* Landrace.wiki – Simple fixed map (MediaWiki compatible) */
(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';

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

    // FIXED: Set zoom limits directly in map options
    var map = L.map(el, {
      minZoom: 2,      // Can't zoom out past world view
      maxZoom: 15,     // Reasonable max zoom for this type of data
      zoomControl: true
    }).setView([15, 105], 5);  // Better initial view for Southeast Asia
    
    // Add the tile layer
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { 
      attribution:'© OSM' 
    }).addTo(map);

    // SIMPLE legend that works with MediaWiki CSS
    var legend = L.control({ position:'bottomleft' });
    legend.onAdd = function () {
      var div = L.DomUtil.create('div', 'lw-legend-map');
      
      // Use inline styles to avoid CSS conflicts
      div.style.cssText = `
        background: white;
        padding: 12px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        border: 1px solid #ccc;
        font-size: 12px;
        line-height: 1.4;
      `;
      
      var html = '<div style="font-weight: bold; margin-bottom: 8px; color: #333;">Conservation Status</div>';
      
      var items = [
        ['#2ecc71', 'Stable'],
        ['#f1c40f', 'Vulnerable'], 
        ['#e67e22', 'Endangered'],
        ['#e74c3c', 'Critical'],
        ['#95a5a6', 'Lost']
      ];
      
      items.forEach(function([color, label]) {
        html += `
          <div style="display: flex; align-items: center; margin: 6px 0;">
            <div style="
              width: 12px; 
              height: 12px; 
              background: ${color}; 
              border-radius: 50%; 
              margin-right: 8px;
              border: 1px solid rgba(0,0,0,0.2);
            "></div>
            <span style="color: #555;">${label}</span>
          </div>
        `;
      });
      
      div.innerHTML = html;
      return div;
    };
    legend.addTo(map);

    var cfg = {
      regions:     { 
        style: f => ({ 
          color: statusColor(f.properties.status), 
          weight: 2, 
          fillOpacity: 0.2,
          opacity: 0.8
        })
      },
      populations: { 
        pointToLayer: (f, ll) => L.circleMarker(ll, { 
          radius: 6, 
          color: '#fff',
          weight: 2,
          fillColor: statusColor(f.properties.status),
          fillOpacity: 0.8
        })
      },
      accessions:  { 
        pointToLayer: (f, ll) => L.circleMarker(ll, { 
          radius: 5, 
          color: '#fff',
          weight: 2,
          fillColor: statusColor(f.properties.status),
          fillOpacity: 0.9
        })
      }
    };

    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()) {
            // Fit bounds but respect zoom limits
            map.fitBounds(b.pad(0.2), {
              maxZoom: 10  // Don't zoom in too much when auto-fitting
            });
            return;
          }
        }
        // Fallback view
        map.setView([15, 105], 5);
      } catch (e) {
        console.error('Map fitting error:', e);
        map.setView([15, 105], 5);
      }
      
      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);
      
      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');
        
        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,-8], opacity:0.9 });
          }
        }, cfg[kind])).addTo(map);
        
        layers.push(layer);
        dataLoadCount++;
        
        // Only fit bounds after all expected data is loaded
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
      }).catch(function(err){
        console.error('[Landrace.wiki map]', kind, err);
        dataLoadCount++;
        
        if (dataLoadCount >= expectedDataSources) {
          maybeFit();
        }
      });
    });

    // If no data sources, immediately set view
    if (expectedDataSources === 0) {
      console.log('No data sources found, using default view');
      map.setView([15, 105], 5);
      setTimeout(function(){ 
        map.invalidateSize(true); 
      }, 100);
    }

    // Add a simple zoom level indicator in the corner
    var zoomDisplay = L.control({ position: 'topright' });
    zoomDisplay.onAdd = function() {
      var div = L.DomUtil.create('div');
      div.style.cssText = `
        background: rgba(255,255,255,0.9);
        padding: 5px 8px;
        border-radius: 4px;
        font-size: 11px;
        color: #666;
        border: 1px solid #ccc;
      `;
      div.innerHTML = 'Zoom: ' + map.getZoom();
      
      map.on('zoomend', function() {
        div.innerHTML = 'Zoom: ' + map.getZoom() + ' (min: 2, max: 15)';
      });
      
      return div;
    };
    zoomDisplay.addTo(map);
  }

  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); 
      });
    }
  });
})();