MediaWiki:Common.js
MediaWiki interface page
More actions
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)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Landrace.wiki – Map with SMW API support */
(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 ({
'Critical (immediate action needed)':'#e74c3c',
'High (action needed within 5 years)':'#e67e22',
'Medium (monitoring required)':'#f1c40f',
'Low (stable, routine documentation)':'#2ecc71'
})[s] || '#3498db';
}
function popup(kind, p) {
if (kind === 'accessions') {
var t = [p.accession_id || p.id, p.local_name || p.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||'');
}
// Convert SMW API results to GeoJSON
function smwToGeoJSON(data) {
var features = [];
var results = data.query ? data.query.results : data.results;
if (!results) {
console.log('No results in SMW response');
return { type: 'FeatureCollection', features: [] };
}
for (var pageName in results) {
var item = results[pageName];
var printouts = item.printouts || {};
// Get coordinates
var coords = printouts['Has GPS coordinates'];
if (!coords || coords.length === 0) continue;
var coord = coords[0];
var lat, lon;
// Handle different coordinate formats from SMW
if (typeof coord === 'object') {
lat = coord.lat;
lon = coord.lon || coord.lng || coord.long;
} else if (typeof coord === 'string') {
// Try to parse "lat, lon" format
var parts = coord.split(',');
if (parts.length === 2) {
lat = parseFloat(parts[0].trim());
lon = parseFloat(parts[1].trim());
}
}
if (!lat || !lon || isNaN(lat) || isNaN(lon)) {
console.log('Invalid coordinates for', pageName, coord);
continue;
}
// Get other properties
var name = printouts['Has descriptive name'];
name = (name && name.length > 0) ? name[0] : pageName;
var status = printouts['Has conservation priority'];
status = (status && status.length > 0) ? status[0] : '';
var accessionId = printouts['Has accession ID'];
accessionId = (accessionId && accessionId.length > 0) ? accessionId[0] : '';
// Handle if accession ID is an object (page link)
if (typeof accessionId === 'object' && accessionId.fulltext) {
accessionId = accessionId.fulltext;
}
features.push({
type: 'Feature',
properties: {
id: accessionId,
name: name,
status: status,
page_url: item.fullurl || ('/wiki/' + encodeURIComponent(pageName))
},
geometry: {
type: 'Point',
coordinates: [lon, lat]
}
});
}
console.log('Converted', features.length, 'features from SMW');
return { type: 'FeatureCollection', features: features };
}
// Fetch data from SMW API
function fetchSMW(query, callback) {
var apiUrl = mw.config.get('wgScriptPath') + '/api.php';
var params = new URLSearchParams({
action: 'ask',
query: query,
format: 'json'
});
console.log('Fetching SMW query:', query);
fetch(apiUrl + '?' + params.toString())
.then(function(r) {
if (!r.ok) throw new Error('SMW API error: ' + r.status);
return r.json();
})
.then(function(data) {
console.log('SMW API response:', data);
var geojson = smwToGeoJSON(data);
callback(null, geojson);
})
.catch(function(err) {
console.error('SMW fetch error:', err);
callback(err, null);
});
}
function initOne(el) {
if (el.dataset.init) return;
el.dataset.init = '1';
if (el.clientHeight < 100) {
el.style.height = '70vh';
}
var map = L.map(el, {
minZoom: 2,
maxZoom: 15,
zoomControl: true
}).setView([15, 105], 5);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:'© OSM'
}).addTo(map);
var legend = L.control({ position:'bottomleft' });
legend.onAdd = function () {
var div = L.DomUtil.create('div', 'lw-legend-map');
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(item) {
var color = item[0];
var label = item[1];
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: function(f) {
return {
color: statusColor(f.properties.status),
weight: 2,
fillOpacity: 0.2,
opacity: 0.8
};
}
},
populations: {
pointToLayer: function(f, ll) {
return L.circleMarker(ll, {
radius: 6,
color: '#fff',
weight: 2,
fillColor: statusColor(f.properties.status),
fillOpacity: 0.8
});
}
},
accessions: {
pointToLayer: function(f, ll) {
return 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 (including smw-query)
['regions','populations','accessions'].forEach(function(kind) {
if (el.dataset[kind]) expectedDataSources++;
});
if (el.dataset.smwQuery) 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.2), {
maxZoom: 10
});
return;
}
}
map.setView([15, 105], 5);
} catch (e) {
console.error('Map fitting error:', e);
map.setView([15, 105], 5);
}
setTimeout(function(){
map.invalidateSize(true);
}, 100);
}
function processGeoJSON(kind, g) {
console.log('Processing', kind, '- features:', g.features ? g.features.length : 'unknown');
if (!g.features || g.features.length === 0) {
console.log('No features to display for', kind);
dataLoadCount++;
if (dataLoadCount >= expectedDataSources) maybeFit();
return;
}
var layer = L.geoJSON(g, Object.assign({
onEachFeature: function(f, ly) {
var p = f.properties || {};
ly.bindPopup(popup(kind, p));
var title = p.accession_id || p.id || p.name || '';
if (title) ly.bindTooltip(title, { direction:'top', offset:[0,-8], opacity:0.9 });
}
}, cfg[kind])).addTo(map);
layers.push(layer);
dataLoadCount++;
if (dataLoadCount >= expectedDataSources) {
maybeFit();
}
}
function loadData(kind, data) {
var trimmed = data.trim();
if (trimmed.charAt(0) === '{' || trimmed.charAt(0) === '[') {
// Inline JSON
try {
var g = JSON.parse(trimmed);
if (Array.isArray(g)) {
g = { type: 'FeatureCollection', features: g };
}
processGeoJSON(kind, g);
} catch (e) {
console.error('[Landrace.wiki map] JSON parse error for', kind, e);
dataLoadCount++;
if (dataLoadCount >= expectedDataSources) maybeFit();
}
} else {
// URL - fetch it
console.log('Loading', kind, 'from', data);
fetch(data).then(function(r) {
if (!r.ok) throw new Error(kind + ' fetch ' + r.status + ' ' + data);
return r.json();
}).then(function(json) {
processGeoJSON(kind, json);
}).catch(function(err) {
console.error('[Landrace.wiki map]', kind, err);
dataLoadCount++;
if (dataLoadCount >= expectedDataSources) maybeFit();
});
}
}
// Load URL/inline data sources
['regions','populations','accessions'].forEach(function(kind) {
var data = el.dataset[kind];
if (!data) return;
loadData(kind, data);
});
// Load SMW query data
if (el.dataset.smwQuery) {
fetchSMW(el.dataset.smwQuery, function(err, geojson) {
if (err) {
dataLoadCount++;
if (dataLoadCount >= expectedDataSources) maybeFit();
return;
}
processGeoJSON('accessions', geojson);
});
}
if (expectedDataSources === 0) {
console.log('No data sources found, using default view');
map.setView([15, 105], 5);
setTimeout(function(){
map.invalidateSize(true);
}, 100);
}
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();
});
return div;
};
zoomDisplay.addTo(map);
}
function init(root) {
(root || document).querySelectorAll('.lw-map').forEach(initOne);
}
addCSS(CDN + 'leaflet.css', 'leaflet-css');
addJS(CDN + 'leaflet.js', function () {
console.log('Leaflet loaded, initializing maps...');
init();
if (window.mw && mw.hook) {
mw.hook('wikipage.content').add(function ($c) {
init($c && $c[0] ? $c[0] : document);
});
}
});
})();