MediaWiki:DataMaps.js

From Deez Nuts' Sword Coast Campaign
Revision as of 19:01, 29 August 2026 by Wvaske (talk | contribs) (Labels: tier relative to the map's fitted zoom; expose current zoom for tuning)
Jump to navigation Jump to 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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * Interactive maps (Extension:DataMaps) site script.
 * Binds a permanent name label to every marker so the maps read like the printed ones,
 * and hides labels of the busier groups (towns, ruins, wilds, rumours) while zoomed far out.
 * Styling lives in MediaWiki:DataMaps.css (.dn-map-label).
 */
mw.loader.using( 'ext.datamaps.bootstrap' ).then( function () {
	var MINOR_GROUPS = [ 'town', 'ruin', 'wilds', 'rumour' ],
		// Minor labels appear once the map is zoomed in this many levels past its fitted (initial) zoom.
		NEAR_DELTA = 0.6;

	mw.dataMaps.registerMapAddedHandler( function ( map ) {
		var isMini = map.rootElement.classList.contains( 'ext-datamaps-mini-layout' );

		map.on( 'markerReady', function ( marker ) {
			var state = marker.apiInstance && marker.apiInstance[ 2 ],
				group = marker.attachedLayers && marker.attachedLayers[ 0 ],
				size, offsetX, cls;
			if ( !state || !state.label || typeof marker.bindTooltip !== 'function' ) {
				return;
			}
			// Sit the label just right of the icon (icons are anchored at their centre).
			size = marker.options && marker.options.icon && marker.options.icon.options.iconSize;
			offsetX = size ? ( Array.isArray( size ) ? size[ 0 ] : size.x || 40 ) / 2 + 2 : 12;
			cls = 'dn-map-label dn-map-label-g-' + ( group || 'none' );
			if ( isMini ) {
				cls += ' dn-map-label-mini';
			}
			if ( MINOR_GROUPS.indexOf( group ) !== -1 ) {
				cls += ' dn-map-label-minor';
			}
			marker.bindTooltip( state.label, {
				permanent: true,
				direction: 'right',
				offset: [ offsetX, 0 ],
				interactive: false,
				opacity: 1,
				className: cls
			} );
		} );

		// Zoom tier → data attribute the CSS keys off. "far" = at or near the fitted zoom.
		map.on( 'leafletLoaded', function () {
			var leafletMap = map.viewport && map.viewport.getLeafletMap(),
				baseZoom = null;
			if ( !leafletMap ) {
				return;
			}
			function updateTier() {
				var z = leafletMap.getZoom();
				if ( baseZoom === null || z < baseZoom ) {
					baseZoom = z; // the most zoomed-out level seen is the fitted view
				}
				map.rootElement.dataset.dnZoom = z.toFixed( 2 );
				map.rootElement.dataset.dnBaseZoom = baseZoom.toFixed( 2 );
				map.rootElement.dataset.dnLabelTier = ( z - baseZoom ) < NEAR_DELTA ? 'far' : 'near';
			}
			leafletMap.on( 'zoomend', updateTier );
			leafletMap.whenReady( updateTier );
		} );
	} );
} );