User

Seb35/bluell.js

< User:Seb35
Revision as of 07:37, 3 September 2021 by Seb35 (talk | contribs)

Note: After saving, 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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
// Development in final phase of the interface for displaying contributions
$( function (){
	if( mw.config.get( 'wgPageName' ) !== 'User:Nicolas_NALLET' ) {
		return;
	}
	var userLanguage = mw.config.get( 'wgUserLanguage' );
	var messages = {
		'no-results': {
			en: 'No results.',
			de: 'Keine Ergebnisse.',
			fr: 'Pas de résultat.',
		}
	};
	mw.loader.using( ['oojs', 'oojs-ui'], function () {

		oouiSelectors = {
			'speaker': null,
			'gender': null,
			'language': null,
			'proficiency': null,
		};
		var sparqlGlobal = {
			'speaker': 'SELECT DISTINCT ?speaker ?speakerLabel WHERE { ?speaker prop:P2 entity:Q3 . ?speaker rdfs:label ?speakerLabel . FILTER( LANG(?speakerLabel) = "en" ) } ORDER BY ?speakerLabel',
			'gender': 'SELECT DISTINCT ?gender ?genderLabel WHERE { ?gender prop:P2 entity:Q7 . SERVICE wikibase:label { bd:serviceParam wikibase:language "' + userLanguage + ',fr,en" } } ORDER BY ?gender',
			'language': 'SELECT DISTINCT ?language ?languageLabel WHERE { ?language prop:P2 entity:Q4 . SERVICE wikibase:label { bd:serviceParam wikibase:language "' + userLanguage + ',fr,en" } } ORDER BY ?languageLabel',
			'proficiency': 'SELECT DISTINCT ?proficiency ?proficiencyLabel WHERE { ?proficiency prop:P2 entity:Q5 . SERVICE wikibase:label { bd:serviceParam wikibase:language "' + userLanguage + ',fr,en" } } ORDER BY ?proficiency',
		};
		var placeholders = {
			'en': {
				'speaker': '👤 Speaker',
				'gender': '♀️ ♂️ Speaker\'s gender',
				'language': '🏳️ Language',
				'proficiency': '🥇 Level of proficiency',
			},
			'fr': {
				'speaker': '👤 Locuteur',
				'gender': '♀️ ♂️ Genre du locuteur',
				'language': '🏳️ Langue',
				'proficiency': '🥇 Niveau de compétence',
			},
		};
		var htmlElements = {
			'speaker': '#filteruser',
			'gender': '#filtergender',
			'language': '#filterlanguage',
			'proficiency': '#filterlevelofproficiency',
		};
		var lastRequest = {
			'speaker': '',
			'gender': '',
			'language': '',
			'proficiency': '',
		};

		function getValueWidget( type ) {
			if( !oouiSelectors[type] ) {
				return '';
			}
			var widgetCombobox = type === 'speaker' || type === 'language';
			if( widgetCombobox ) {
				return oouiSelectors[type].getValue();
			} else {
				return oouiSelectors[type].getMenu().findSelectedItem() ? oouiSelectors[type].getMenu().findSelectedItem().getData() : '';
			}
			
		}

		function updateSelector( type ) {
			return function( values ) {
				/*if( ( getValueWidget( 'speaker' ) != lastRequest['speaker'] ) ||
				    ( getValueWidget( 'gender' ) != lastRequest['gender'] ) ||
				    ( getValueWidget( 'language' ) != lastRequest['language'] ) ||
				    ( getValueWidget( 'proficiency' ) != lastRequest['proficiency'] ) ) {
					return;
				}*/

				var widgetType = type === 'speaker' || type === 'language' ? 'ComboBoxInputWidget' : 'DropdownWidget';
				var v = values.results.bindings;
				console.log( type );
				console.log( v );
				console.log( v.length === 1 ? v[0][ type + 'Label' ].value + " (" + v[0][type].value.substr( 31 ) + ")" : null );
				oouiSelectors[type] = new OO.ui[widgetType]( {
					placeholder: placeholders[userLanguage][type] ? placeholders[userLanguage][type] : placeholders['en'][type],
					disabled: v.length === 1,
					menu: {
						filterFromInput: true,				
						items: v.map( function( x ) {
							return new OO.ui.MenuOptionWidget( {
								data: x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")",
								label: x[ type + 'Label' ].value
							} );
						} )
					}
				} );
				if( v.length === 1 ) {
					if( widgetType === 'ComboBoxInputWidget' ) {
						oouiSelectors[type].setValue( v[0][ type + 'Label' ].value + " (" + v[0][type].value.substr( 31 ) + ")" );
					} else {
						oouiSelectors[type].getMenu().selectItemByData( v[0][ type + 'Label' ].value + " (" + v[0][type].value.substr( 31 ) + ")" );
					}
				}

				$( htmlElements[type] ).html('').append(
					oouiSelectors[type].$element
				);

				function onChange() {
					console.log( 'event onChange ' + type );
					doQuery();
					doQuery( 'speaker' );
					doQuery( 'gender' );
					doQuery( 'language' );
					doQuery( 'proficiency' );
				}
				if( widgetType === 'ComboBoxInputWidget' ) {
					oouiSelectors[type].on( 'change', onChange );
				} else {
					oouiSelectors[type].getMenu().on( 'change', onChange );
				}

			};
		}

		$.getJSON(
			'https://lingualibre.org/bigdata/namespace/wdq/sparql',
			{
				query: sparqlGlobal['speaker']
			}
		).done( updateSelector( 'speaker' ) );

		$.getJSON(
			'https://lingualibre.org/bigdata/namespace/wdq/sparql',
			{
				query: sparqlGlobal['gender']
			}
		).done( updateSelector( 'gender' ) );

		$.getJSON(
			'https://lingualibre.org/bigdata/namespace/wdq/sparql',
			{
				query: sparqlGlobal['language']
			}
		).done( updateSelector( 'language' ) );

		$.getJSON(
			'https://lingualibre.org/bigdata/namespace/wdq/sparql',
			{
				query: sparqlGlobal['proficiency']
			}
		).done( updateSelector( 'proficiency' ) );

		function reset() {
			oouiSelectors['speaker'].setDisabled( false ).setValue( null );
			oouiSelectors['language'].setDisabled( false ).setValue( null );
			oouiSelectors['gender'].setDisabled( false ).getMenu().selectItemByData( null );
			oouiSelectors['proficiency'].setDisabled( false ).getMenu().selectItemByData( null );
		}

		$( '#resetsearch' ).html('').append(
			( new OO.ui.ButtonInputWidget( {
				label: 'Reset'
			} ) ).on( 'click', reset ).$element
		);

		// Display results
		function createAudioBoxesForSearch( data ) {
			if ( data.results === undefined || data.results.bindings === undefined ) {
				displayError( 'error: no result from SPARQL' );
				return;
			}
			if ( data.results.bindings.length < 1 ) {
				$( '#audioresults' ).html( messages['no-results'][userLanguage] ? messages['no-results'][userLanguage] : messages['no-results']['en'] );
				return;
			}
			var length = data.results.bindings.length;
			console.log( data.results.bindings );
			function displayAudioBoxes( index ) {
				$( '#audioresults' ).html( '' );
				console.log( 'index', index );
				for( var i = 0; i < 10 && i+index*10 < length; i++ ) {
					console.log( 'i effectif', i+index*10 );
					var box = $( '<div class="audiobox"> <div class="ab-playbutton"><i></i></div> <div> <div class="ab-title">...</div> <div class="ab-metadata">...</div> </div> </div>' );
					var audiobox = new AudioBox( data.results.bindings[ i+index*10 ].record.value.substr( 31 ), box );
					$( '#audioresults' ).append( box );
					//ab1 = new AudioBox( data.query.rwrecords[ i ], $( '.audiobox' ).eq( i ) );
					//$("body").append('<div class="audiobox"> <div class="ab-playbutton"><i></i></div> <div> <div class="ab-title">...</div> <div class="ab-metadata">...</div> </div> </div>');	
				}
				function applyFn( i ) {
					return function() {
						console.log( i );
						displayAudioBoxes( i );
						return false;
					}
				}
				for( var i = 0; i < Math.ceil( length/10 ); i++ ) {
					var link = $( '<a href="#">' + (i+1) + '</a>' ).on( 'click', applyFn( i ) );
					$( '#audioresults' ).append( link ).append( ' ' );
				}
			}
			displayAudioBoxes( 0 );
		}

		// Do SPARQL request from filters
		function doQuery( variable ){

			// Do not modify a selector where there is a value
			if( variable && getValueWidget( variable ) ) {
				return;
			}

			function getQ( type ) {
				if( variable === type ) {
					return '?' + type;
				}
				var text = getValueWidget( type );
				if( !text ) {
					return '';
				}
				text = text.trim();
				if( /^Q[0-9]+$/.test( text ) ) {
					return 'entity:' + text;
				} else if( /\((Q[0-9]+)\)$/.test( text ) ) {
					return 'entity:' + text.replace( /.*\((Q[0-9]+)\)$/, '$1' );
				} else {
					return '';
				}
			}

			var speaker = getQ( 'speaker' ),
			    gender = getQ( 'gender' ),
			    language = getQ( 'language' ),
			    proficiency = getQ( 'proficiency' ),
			    somevalue = false;
			if( ! variable ) {
				lastRequest = {
					'speaker': getValueWidget( 'speaker' ),
					'gender': getValueWidget( 'gender' ),
					'language': getValueWidget( 'language' ),
					'proficiency': getValueWidget( 'proficiency' ),
				};
			}
			console.log( 'doQuery( "' + variable + '" );' );
			console.log( speaker, gender, language, proficiency, lastRequest );

			// When all fields are empty, do not query
			if( !speaker && !gender && !language && !proficiency ) {
				return;
			}

			var query = "SELECT " + ( variable ? 'DISTINCT ?' + variable + ' ?' + variable + 'Label' : "?record" ) + " WHERE { ?record prop:P2 entity:Q2 ; prop:P4 ?language ; prop:P5 ?speaker . ";
			if( speaker ) {
				query += "?record prop:P5 " + speaker + " . ";
				somevalue = true;
			}
			if( gender ) {
				query += "?record prop:P5 [ prop:P8 " + gender + " ] . ";
				somevalue = true;
			}
			if( language ) {
				query += "?record prop:P4 " + language + " . ";
				somevalue = true;
			}
			if( proficiency ) {
				query += "?speaker llp:P4 [ llv:P4 ?language ; llq:P16 " + proficiency + " ] . ";
				somevalue = true;
			}
			query += "SERVICE wikibase:label { bd:serviceParam wikibase:language '" + userLanguage + ",en,fr' } } LIMIT 100";

			if( variable ) {
				if( !somevalue ) {
					query = sparqlGlobal[variable];
				}
			} else {
				if( !variable && !somevalue ) {
					return;
				}
				// Voir https://commons.wikimedia.org/wiki/Category:Throbbers - il faut que le fond soit transparent
				$( '#audioresults' ).html( '' ).append( '<img src="https://upload.wikimedia.org/wikipedia/commons/7/7a/Balls.gif" width="50" />' );
			}

			// Execute the request
			var result = $.getJSON(
				'https://lingualibre.org/bigdata/namespace/wdq/sparql',
				{
					query: query,
					//Accept: 'application/sparql-results+json'
				}
			);

			// Depending if we want the whole results or update on selector
			if( variable ) {
				result.then( updateSelector( variable ), displayError );
			} else {
				result.then( createAudioBoxesForSearch, displayError );
			}
		}

	} );

} );