MediaWiki:Gadget-Bahnsteiganzeiger.js

Version vom 9. Juli 2026, 19:47 Uhr von Admin (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „/** * Gadget-Bahnhof_anlegen.js * ============================================================================ * Komfortables Anlegen von Bahnhofsseiten. Button erscheint nur auf der Seite * "Bahnhof anlegen" und nur für angemeldete Nutzer. * * Erzeugt eine Seite "Bahnhof <Name>" mit: * - Breadcrumb + 🌐 Website * - WikiMap-Karte (aktiver Ort = Seitentitel, Filter "Bahnhof") * - Standort-Zeilen (📍 Adresse, OSM, 🧭 Koordinaten, CoMap…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
/**
 * Gadget-Bahnhof_anlegen.js
 * ============================================================================
 * Komfortables Anlegen von Bahnhofsseiten. Button erscheint nur auf der Seite
 * "Bahnhof anlegen" und nur für angemeldete Nutzer.
 *
 * Erzeugt eine Seite "Bahnhof <Name>" mit:
 *   - Breadcrumb + 🌐 Website
 *   - WikiMap-Karte (aktiver Ort = Seitentitel, Filter "Bahnhof")
 *   - Standort-Zeilen (📍 Adresse, OSM, 🧭 Koordinaten, CoMaps, Google Maps)
 *     mit denselben Auto-Links aus Koordinaten wie das Eventform-Gadget
 *   - Abschnitt "Monitore" mit zwei Bahnsteiganzeigern (dep/arr) und je einem
 *     Link zur detaillierten ÖBB-Tafel
 *
 * Die evaId wird von Hand eingetragen ODER über eine Namenssuche gewählt
 * (ÖBB-Daten via v6.oebb.transport.rest – nur beim Anlegen, nicht im Betrieb).
 * Die WikiMap-Orte.json wird NICHT angefasst (pflegst du selbst).
 * ============================================================================
 */
( function () {
	'use strict';

	// Button nur auf dieser Seite (wgPageName nutzt Unterstriche).
	if ( mw.config.get( 'wgPageName' ) !== 'Bahnhof_anlegen' ) {
		return;
	}
	if ( !mw.config.get( 'wgUserName' ) ) {
		return;
	}

	function v( val ) {
		return ( val || '' ).trim();
	}

	/* ------------------------------------------------------------------ *
	 * Koordinaten-Parsing + Link-Bau – identisch zum Eventform-Gadget.
	 * ------------------------------------------------------------------ */
	function parseCoordinates( input ) {
		if ( !input ) {
			return null;
		}
		var s = input.trim();
		var m;

		m = /^(-?\d+,\d+)\s*[;\s]\s*(-?\d+,\d+)$/.exec( s ) ||
			/^(-?\d+,\d+),\s+(-?\d+,\d+)$/.exec( s );
		if ( m ) {
			var latDE = parseFloat( m[ 1 ].replace( ',', '.' ) );
			var lngDE = parseFloat( m[ 2 ].replace( ',', '.' ) );
			if ( isFinite( latDE ) && isFinite( lngDE ) &&
				Math.abs( latDE ) <= 90 && Math.abs( lngDE ) <= 180 ) {
				return { lat: latDE, lng: lngDE };
			}
		}

		m = /^(-?\d+(?:\.\d+)?)\s*[,;\s]\s*(-?\d+(?:\.\d+)?)$/.exec( s );
		if ( m ) {
			var lat = parseFloat( m[ 1 ] );
			var lng = parseFloat( m[ 2 ] );
			if ( isFinite( lat ) && isFinite( lng ) &&
				Math.abs( lat ) <= 90 && Math.abs( lng ) <= 180 ) {
				return { lat: lat, lng: lng };
			}
		}

		m = /^(\d+(?:[.,]\d+)?)\s*°?\s*([NS])\s*[,;\s]?\s*(\d+(?:[.,]\d+)?)\s*°?\s*([EW])$/i.exec( s );
		if ( m ) {
			var lat2 = parseFloat( m[ 1 ].replace( ',', '.' ) );
			if ( m[ 2 ].toUpperCase() === 'S' ) { lat2 = -lat2; }
			var lng2 = parseFloat( m[ 3 ].replace( ',', '.' ) );
			if ( m[ 4 ].toUpperCase() === 'W' ) { lng2 = -lng2; }
			if ( isFinite( lat2 ) && isFinite( lng2 ) &&
				Math.abs( lat2 ) <= 90 && Math.abs( lng2 ) <= 180 ) {
				return { lat: lat2, lng: lng2 };
			}
		}

		m = /^(\d+)\s*°\s*(\d+)\s*['\u2019\u2032]\s*(\d+(?:[.,]\d+)?)\s*["\u201D\u2033]\s*([NS])\s*[,;\s]?\s*(\d+)\s*°\s*(\d+)\s*['\u2019\u2032]\s*(\d+(?:[.,]\d+)?)\s*["\u201D\u2033]\s*([EW])$/i.exec( s );
		if ( m ) {
			var lat3 = parseInt( m[ 1 ], 10 ) + parseInt( m[ 2 ], 10 ) / 60 + parseFloat( m[ 3 ].replace( ',', '.' ) ) / 3600;
			if ( m[ 4 ].toUpperCase() === 'S' ) { lat3 = -lat3; }
			var lng3 = parseInt( m[ 5 ], 10 ) + parseInt( m[ 6 ], 10 ) / 60 + parseFloat( m[ 7 ].replace( ',', '.' ) ) / 3600;
			if ( m[ 8 ].toUpperCase() === 'W' ) { lng3 = -lng3; }
			if ( Math.abs( lat3 ) <= 90 && Math.abs( lng3 ) <= 180 ) {
				return { lat: lat3, lng: lng3 };
			}
		}

		m = /^(\d+)\s*°\s*(\d+(?:[.,]\d+)?)\s*['\u2019\u2032]\s*([NS])\s*[,;\s]?\s*(\d+)\s*°\s*(\d+(?:[.,]\d+)?)\s*['\u2019\u2032]\s*([EW])$/i.exec( s );
		if ( m ) {
			var lat4 = parseInt( m[ 1 ], 10 ) + parseFloat( m[ 2 ].replace( ',', '.' ) ) / 60;
			if ( m[ 3 ].toUpperCase() === 'S' ) { lat4 = -lat4; }
			var lng4 = parseInt( m[ 4 ], 10 ) + parseFloat( m[ 5 ].replace( ',', '.' ) ) / 60;
			if ( m[ 6 ].toUpperCase() === 'W' ) { lng4 = -lng4; }
			if ( Math.abs( lat4 ) <= 90 && Math.abs( lng4 ) <= 180 ) {
				return { lat: lat4, lng: lng4 };
			}
		}

		return null;
	}

	function fmtCoord( n ) {
		return n.toFixed( 7 );
	}
	function buildOsmUrl( c ) {
		var lat = fmtCoord( c.lat ), lng = fmtCoord( c.lng );
		return 'https://www.openstreetmap.org/?mlat=' + lat + '&mlon=' + lng + '#map=17/' + lat + '/' + lng;
	}
	function buildGoogleMapsUrl( c ) {
		return 'https://www.google.com/maps?q=' + fmtCoord( c.lat ) + ',' + fmtCoord( c.lng );
	}
	function buildCoMapsUrl( c ) {
		// CoMaps/Organic Maps öffnen Koordinaten über das geo:-URI (RFC 5870).
		return 'geo:' + fmtCoord( c.lat ) + ',' + fmtCoord( c.lng );
	}

	/* ------------------------------------------------------------------ *
	 * ÖBB-Detaillink (volle Tafel) – input + sqView, mit newrequest.
	 * ------------------------------------------------------------------ */
	function baueDetailUrl( eva, typ ) {
		var boardType = ( typ === 'arr' ) ? 'arr' : 'dep';
		var sqView = ( typ === 'arr' ) ? '3' : '2';
		return 'https://fahrplan.oebb.at/bin/stboard.exe/dn?protocol=https:&input=' +
			encodeURIComponent( eva ) +
			'&boardType=' + boardType +
			'&sqView=' + sqView +
			'&productsFilter=1111111111111&maxJourneys=40&start=yes&newrequest=yes&';
	}

	/* ------------------------------------------------------------------ *
	 * Verkehrsmittel-Kürzel für die Trefferliste.
	 * ------------------------------------------------------------------ */
	function prods( p ) {
		if ( !p ) {
			return '';
		}
		var map = {
			nationalExpress: 'RJ/EC', national: 'IC/D', regionalExpress: 'REX',
			regional: 'R/S', suburban: 'S-Bahn', bus: 'Bus', tram: 'Tram',
			subway: 'U', ferry: 'Fähre'
		};
		var out = [];
		Object.keys( map ).forEach( function ( k ) {
			if ( p[ k ] ) { out.push( map[ k ] ); }
		} );
		return out.length ? ' – ' + out.join( ', ' ) : '';
	}

	/* ------------------------------------------------------------------ *
	 * Wikitext der Bahnhofsseite.
	 * ------------------------------------------------------------------ */
	function buildWikitext( f ) {
		var L = [];
		L.push( '[[Hauptseite]] > [[Hauptseite#Öffentlicher Verkehr|Öffentlicher Verkehr]] > [[Zug]] > [[Zug#Bahnhöfe|Bahnhöfe]]' );

		if ( f.website ) {
			L.push( '🌐 ' + f.website );
		}

		// Karte: aktiver Ort = Seitentitel, nur Bahnhof-Pins.
		L.push( '<div class="wikimap" data-aktiv-ort="' + f.titel + '" data-filter="Bahnhof"></div>' );
		L.push( '' );

		// Standort-Zeilen – jede in eigenem Absatz (Leerzeile dazwischen).
		var first = true;
		function loc( line ) {
			if ( !first ) { L.push( '' ); }
			L.push( line );
			first = false;
		}
		if ( f.adresse ) { loc( '📍 ' + f.adresse ); }
		if ( f.osmUrl ) { loc( '[[file:osm.png|24px|link=]] ' + f.osmUrl ); }
		if ( f.koordinaten ) { loc( '🧭 ' + f.koordinaten ); }
		if ( f.comapsUrl ) { loc( '[[file:CoMaps.png|24px|link=]] ' + f.comapsUrl ); }
		if ( f.gmapsUrl ) { loc( '[[file:GoogleMaps.png|24px|link=]] ' + f.gmapsUrl ); }

		// Monitore (intern: Bahnsteiganzeiger).
		L.push( '== Monitore ==' );
		L.push( '<div class="bahnsteiganzeiger" data-evaid="' + f.evaId + '" data-typ="dep"></div>' );
		L.push( '' );
		L.push( '[' + baueDetailUrl( f.evaId, 'dep' ) + ' Zur detaillierten Abfahrtstafel]' );
		L.push( '' );
		L.push( '<div class="bahnsteiganzeiger" data-evaid="' + f.evaId + '" data-typ="arr"></div>' );
		L.push( '' );
		L.push( '[' + baueDetailUrl( f.evaId, 'arr' ) + ' Zur detaillierten Ankunftstafel]' );

		return L.join( '\n' );
	}

	/* ------------------------------------------------------------------ *
	 * Oberfläche.
	 * ------------------------------------------------------------------ */
	mw.loader.using( [
		'oojs-ui-core',
		'oojs-ui-windows',
		'oojs-ui.styles.icons-interactions',
		'oojs-ui.styles.icons-content',
		'mediawiki.api',
		'mediawiki.util'
	] ).then( function () {

		function BahnhofDialog( config ) {
			BahnhofDialog.super.call( this, config );
		}
		OO.inheritClass( BahnhofDialog, OO.ui.ProcessDialog );

		BahnhofDialog.static.name = 'bahnhofDialog';
		BahnhofDialog.static.title = 'Neuen Bahnhof anlegen';
		BahnhofDialog.static.actions = [
			{ action: 'save', label: 'Seite anlegen', flags: [ 'primary', 'progressive' ] },
			{ label: 'Abbrechen', flags: 'safe' }
		];

		BahnhofDialog.prototype.initialize = function () {
			BahnhofDialog.super.prototype.initialize.apply( this, arguments );
			var dialog = this;

			this.panel = new OO.ui.PanelLayout( { padded: true, expanded: false } );

			this.nameInput = new OO.ui.TextInputWidget( { placeholder: 'z.B. Pottschach', required: true } );

			this.sucheInput = new OO.ui.TextInputWidget( { placeholder: 'Bahnhof suchen …' } );
			this.sucheButton = new OO.ui.ButtonWidget( { label: 'Suchen', icon: 'search' } );
			this.sucheStatus = new OO.ui.LabelWidget( { label: '' } );
			this.sucheAuswahl = new OO.ui.RadioSelectWidget();
			this.sucheAuswahl.toggle( false );

			this.evaidInput = new OO.ui.TextInputWidget( { placeholder: 'z.B. 1131851', required: true } );
			this.pruefButton = new OO.ui.ButtonWidget( { label: 'Prüfen', icon: 'linkExternal' } );

			this.websiteInput = new OO.ui.TextInputWidget( { placeholder: 'https://bahnhof.oebb.at/…' } );
			this.adresseInput = new OO.ui.TextInputWidget( { placeholder: '2630 Pottschach, Putzmannsdorfer Straße 2' } );
			this.koordinatenInput = new OO.ui.TextInputWidget( { placeholder: '47.69694, 16.00583' } );
			this.osmUrlInput = new OO.ui.TextInputWidget( { placeholder: 'https://www.openstreetmap.org/…' } );
			this.comapsUrlInput = new OO.ui.TextInputWidget( { placeholder: 'https://comaps.at/…' } );
			this.gmapsUrlInput = new OO.ui.TextInputWidget( { placeholder: 'https://maps.app.goo.gl/…' } );

			// Suche auslösen
			this.sucheButton.on( 'click', function () { dialog.sucheStarten(); } );
			this.sucheInput.on( 'enter', function () { dialog.sucheStarten(); } );

			// Treffer gewählt -> evaId (und ggf. Name) übernehmen
			this.sucheAuswahl.on( 'choose', function ( item ) {
				var d = item.getData();
				dialog.evaidInput.setValue( String( d.id ).replace( /^0+/, '' ) );
				if ( !v( dialog.nameInput.getValue() ) ) {
					dialog.nameInput.setValue( d.name );
				}
			} );

			// evaId im Browser prüfen
			this.pruefButton.on( 'click', function () {
				var eva = v( dialog.evaidInput.getValue() ).replace( /^0+/, '' );
				if ( !eva ) { return; }
				window.open( baueDetailUrl( eva, 'dep' ), '_blank', 'noopener' );
			} );

			var fsPflicht = new OO.ui.FieldsetLayout( { label: 'Bahnhof (Pflicht)' } );
			fsPflicht.addItems( [
				new OO.ui.FieldLayout( this.nameInput, {
					label: 'Bahnhofsname', align: 'left',
					help: 'Wird zu „Bahnhof <Name>" – das ist Seitentitel UND Karten-ID (data-aktiv-ort). Der gleichnamige Eintrag muss in WikiMap-Orte.json existieren.'
				} ),
				new OO.ui.ActionFieldLayout( this.sucheInput, this.sucheButton, {
					label: 'evaId suchen', align: 'top',
					help: 'Namen eingeben, suchen, den richtigen Treffer wählen – die evaId wird unten eingetragen. Bei mehreren Treffern: der Bahnhof, nicht die Bushaltestelle. Klappt die Suche nicht, evaId manuell eintragen.'
				} ),
				new OO.ui.FieldLayout( this.sucheStatus, { align: 'top', label: ' ' } ),
				new OO.ui.FieldLayout( this.sucheAuswahl, { align: 'top', label: ' ' } ),
				new OO.ui.ActionFieldLayout( this.evaidInput, this.pruefButton, {
					label: 'evaId', align: 'left',
					help: 'Nur Ziffern, z.B. 1131851. „Prüfen" öffnet die ÖBB-Detailtafel dieser evaId in einem neuen Tab zur Kontrolle.'
				} )
			] );

			var fsStandort = new OO.ui.FieldsetLayout( { label: 'Standort (optional)' } );
			fsStandort.addItems( [
				new OO.ui.FieldLayout( this.websiteInput, {
					label: '🌐 Website', align: 'left',
					help: 'z.B. die ÖBB-Bahnhofsseite. Steht als erste Zeile oben; das Panorama kommt später von Hand darüber.'
				} ),
				new OO.ui.FieldLayout( this.adresseInput, { label: '📍 Adresse', align: 'left' } ),
				new OO.ui.FieldLayout( this.koordinatenInput, {
					label: '🧭 Koordinaten', align: 'left',
					help: 'Akzeptiert u.a.: 47.69694, 16.00583 · deutsches Komma-Format · 47°45\'00"N 15°40\'48"E. Wenn gesetzt, werden für leere OSM/CoMaps/Google-Maps-Felder automatisch Links erzeugt. (Der Karten-Pin kommt aus WikiMap-Orte.json, nicht von hier.)'
				} ),
				new OO.ui.FieldLayout( this.osmUrlInput, {
					label: 'OpenStreetMap-URL', align: 'left',
					help: 'Leer lassen -> wird bei gegebenen Koordinaten automatisch erzeugt.'
				} ),
				new OO.ui.FieldLayout( this.comapsUrlInput, {
					label: 'CoMaps-URL', align: 'left',
					help: 'Leer lassen -> wird bei gegebenen Koordinaten automatisch erzeugt.'
				} ),
				new OO.ui.FieldLayout( this.gmapsUrlInput, {
					label: 'Google-Maps-URL', align: 'left',
					help: 'Leer lassen -> wird bei gegebenen Koordinaten automatisch erzeugt.'
				} )
			] );

			this.panel.$element.append( fsPflicht.$element, fsStandort.$element );
			this.$body.append( this.panel.$element );
		};

		// Stationssuche über transport.rest (nur beim Anlegen).
		BahnhofDialog.prototype.sucheStarten = function () {
			var dialog = this;
			var term = v( this.sucheInput.getValue() );
			this.sucheAuswahl.clearItems();
			this.sucheAuswahl.toggle( false );
			if ( !term ) {
				this.sucheStatus.setLabel( 'Bitte einen Namen eingeben.' );
				return;
			}
			this.sucheStatus.setLabel( 'Suche …' );
			var url = 'https://v6.oebb.transport.rest/locations?query=' +
				encodeURIComponent( term ) + '&results=8&poi=false&addresses=false&stops=true';
			fetch( url, { headers: { Accept: 'application/json' } } )
				.then( function ( r ) {
					if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); }
					return r.json();
				} )
				.then( function ( list ) {
					var stops = ( list || [] ).filter( function ( x ) {
						return x && ( x.type === 'stop' || x.type === 'station' ) && x.id;
					} );
					if ( !stops.length ) {
						dialog.sucheStatus.setLabel( 'Keine Station gefunden – evaId ggf. manuell eintragen.' );
						return;
					}
					var items = stops.map( function ( s ) {
						return new OO.ui.RadioOptionWidget( {
							data: { id: s.id, name: s.name },
							label: s.name + '  (evaId ' + String( s.id ).replace( /^0+/, '' ) + ')' + prods( s.products )
						} );
					} );
					dialog.sucheAuswahl.addItems( items );
					dialog.sucheAuswahl.toggle( true );
					dialog.sucheStatus.setLabel( stops.length + ' Treffer – den richtigen auswählen:' );
				} )
				.catch( function ( err ) {
					dialog.sucheStatus.setLabel( 'Suche nicht möglich (' + err.message + ') – bitte evaId manuell eintragen.' );
				} );
		};

		BahnhofDialog.prototype.getActionProcess = function ( action ) {
			var dialog = this;
			function fehler( msg ) {
				return $.Deferred().reject( new OO.ui.Error( msg, { recoverable: true } ) ).promise();
			}
			if ( action === 'save' ) {
				return new OO.ui.Process( function () {
					var name = v( dialog.nameInput.getValue() );
					var evaId = v( dialog.evaidInput.getValue() ).replace( /^0+/, '' );

					if ( !name ) {
						return fehler( 'Bitte den Bahnhofsnamen ausfüllen.' );
					}
					if ( !/^\d+$/.test( evaId ) ) {
						return fehler( 'Bitte eine gültige evaId (nur Ziffern) eintragen.' );
					}

					var titel = /^Bahnhof\s/i.test( name ) ? name : 'Bahnhof ' + name;

					var fields = {
						titel: titel,
						evaId: evaId,
						website: v( dialog.websiteInput.getValue() ),
						adresse: v( dialog.adresseInput.getValue() ),
						koordinaten: v( dialog.koordinatenInput.getValue() ),
						osmUrl: v( dialog.osmUrlInput.getValue() ),
						comapsUrl: v( dialog.comapsUrlInput.getValue() ),
						gmapsUrl: v( dialog.gmapsUrlInput.getValue() )
					};

					var coords = parseCoordinates( fields.koordinaten );
					if ( coords ) {
						if ( !fields.osmUrl ) { fields.osmUrl = buildOsmUrl( coords ); }
						if ( !fields.comapsUrl ) { fields.comapsUrl = buildCoMapsUrl( coords ); }
						if ( !fields.gmapsUrl ) { fields.gmapsUrl = buildGoogleMapsUrl( coords ); }
					}

					var wikitext = buildWikitext( fields );
					var api = new mw.Api();

					return api.get( {
						action: 'query', titles: titel, formatversion: 2
					} ).then( function ( data ) {
						var page = data.query.pages[ 0 ];
						if ( !page.missing ) {
							return fehler( 'Eine Seite „' + titel + '" existiert bereits.' );
						}
						return api.postWithToken( 'csrf', {
							action: 'edit',
							title: titel,
							text: wikitext,
							createonly: true,
							summary: 'Bahnhofsseite über Bahnhof-anlegen-Gadget angelegt'
						} );
					} ).then( function () {
						window.location.href = mw.util.getUrl( titel );
					}, function ( err ) {
						if ( err instanceof OO.ui.Error ) {
							return $.Deferred().reject( err ).promise();
						}
						return fehler( 'Fehler beim Anlegen: ' + ( err && err.toString ? err.toString() : 'unbekannt' ) );
					} );
				} );
			}
			return BahnhofDialog.super.prototype.getActionProcess.call( this, action );
		};

		BahnhofDialog.prototype.getBodyHeight = function () {
			return 640;
		};

		var $container = $( '#bahnhof-form-container' );
		if ( !$container.length ) {
			$container = $( '<div id="bahnhof-form-container"></div>' )
				.appendTo( '#mw-content-text .mw-parser-output' );
		}

		var button = new OO.ui.ButtonWidget( {
			label: 'Neuen Bahnhof anlegen',
			flags: [ 'primary', 'progressive' ],
			icon: 'add'
		} );

		var windowManager = new OO.ui.WindowManager();
		$( document.body ).append( windowManager.$element );
		var dialog = new BahnhofDialog( { size: 'large' } );
		windowManager.addWindows( [ dialog ] );

		button.on( 'click', function () {
			windowManager.openWindow( dialog );
		} );

		$container.empty().append( button.$element );

	} );
}() );