User

Difference between revisions of "Seb35/bluell.js"

< User:Seb35

(correction du bug sous Windows (enfin, j’espère))
(nouvelle version fortement optimisée, avec désormais 4 requête SPARQL initiales (dont une un peu plus grosse que la précédente équivalente, mais celles-ci sont toutes en cache commun), puis 1 seule requête pour obtenir les résultats (aucune pour mettre à jour les sélecteurs, l’info est dans la grosse requête initiale))
Line 4: Line 4:
 
return;
 
return;
 
}
 
}
var userLanguage = mw.config.get( 'wgUserLanguage' );
+
const userLanguage = mw.config.get( 'wgUserLanguage' );
var messages = {
+
const messages = {
'no-results': {
+
'msg-no-results': {
 
en: 'No results.',
 
en: 'No results.',
 
de: 'Keine Ergebnisse.',
 
de: 'Keine Ergebnisse.',
 
fr: 'Pas de résultat.',
 
fr: 'Pas de résultat.',
 +
//qqq: 'Message when there are no results.',
 
},
 
},
'gosearch': {
+
'button-gosearch': {
 
en: 'Search',
 
en: 'Search',
 
de: 'Suchen',
 
de: 'Suchen',
 
fr: 'Rechercher',
 
fr: 'Rechercher',
 +
//qqq: 'Button where the user clicks to search.',
 
},
 
},
'resetsearch': {
+
'button-resetsearch': {
 
en: 'Reset',
 
en: 'Reset',
 
de: 'Löschen',
 
de: 'Löschen',
 
fr: 'Effacer',
 
fr: 'Effacer',
 +
//qqq: 'Button where the user clicks to reset the form.',
 +
},
 +
'placeholder-speaker': {
 +
en: '👤 Speaker',
 +
fr: '👤 Locuteur',
 +
//qqq: 'Placeholder for the field Speaker.',
 +
},
 +
'placeholder-gender': {
 +
en: '♀️ ♂️ Speaker\'s gender',
 +
fr: '♀️ ♂️ Genre du locuteur',
 +
//qqq: 'Placeholder for the field Gender.',
 +
},
 +
'placeholder-language': {
 +
en: '🏳️ Language',
 +
fr: '🏳️ Langue',
 +
//qqq: 'Placeholder for the field Language.',
 +
},
 +
'placeholder-proficiency': {
 +
en: '🥇 Level of proficiency',
 +
fr: '🥇 Niveau de compétence',
 +
//qqq: 'Placeholder for the field Proficiency.',
 
},
 
},
 
};
 
};
Line 31: Line 54:
 
};
 
};
 
var sparqlGlobal = {
 
var sparqlGlobal = {
'speaker': 'SELECT DISTINCT ?speaker ?speakerLabel WHERE { ?speaker prop:P2 entity:Q3 . ?speaker rdfs:label ?speakerLabel . FILTER( LANG(?speakerLabel) = "en" ) } ORDER BY ?speakerLabel',
+
'speaker': 'SELECT ?speaker ?speakerLabel ?gender ?language ?proficiency WHERE { ?speaker prop:P2 entity:Q3 . OPTIONAL { ?speaker prop:P8 ?gender } . OPTIONAL { ?speaker llp:P4 ?statement . ?statement llv:P4 ?language . OPTIONAL { ?statement llq:P16 ?proficiency } } . SERVICE wikibase:label { bd:serviceParam wikibase:language "' + userLanguage + ',fr,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',
 
'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',
 
'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',
 
'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 = {
+
const htmlElements = {
'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',
 
'speaker': '#filteruser',
 
'gender': '#filtergender',
 
'gender': '#filtergender',
Line 56: Line 65:
 
'proficiency': '#filterlevelofproficiency',
 
'proficiency': '#filterlevelofproficiency',
 
};
 
};
var lastRequest = {
+
const unknown = {};
 +
 
 +
let request = {
 
'speaker': '',
 
'speaker': '',
 
'gender': '',
 
'gender': '',
 
'language': '',
 
'language': '',
 
'proficiency': '',
 
'proficiency': '',
 +
}, lastRequest = {
 +
'speaker': '',
 +
'gender': '',
 +
'language': '',
 +
'proficiency': '',
 +
}, speakersCriteria = [];
 +
const list = {
 +
'speaker': [],
 +
'gender': [],
 +
'language': [],
 +
'proficiency': [],
 +
}, mapping = {
 +
'speaker': [],
 +
'gender': [],
 +
'language': [],
 +
'proficiency': [],
 
};
 
};
 
var resetSelectors = false;
 
var resetSelectors = false;
  
function getValueWidget( type ) {
+
// Helper function to obtain the Qvalue of some selector
if( !oouiSelectors[type] ) {
+
function getQValue( type ) {
 +
let rawValue;
 +
if( type === 'speaker' || type === 'language' ) {
 +
rawValue = oouiSelectors[type].getValue();
 +
} else {
 +
rawValue = oouiSelectors[type].getMenu().findSelectedItem() ? oouiSelectors[type].getMenu().findSelectedItem().getData() : '';
 +
}
 +
rawValue = rawValue.trim();
 +
if( !rawValue ) {
 +
return '';
 +
} else if( /^Q[0-9]+$/.test( rawValue ) ) {
 +
return rawValue;
 +
} else if( /\((Q[0-9]+)\)$/.test( rawValue ) ) {
 +
return rawValue.replace( /.*\((Q[0-9]+)\)$/, '$1' );
 +
} else {
 
return '';
 
return '';
 
}
 
}
var widgetCombobox = type === 'speaker' || type === 'language';
+
}
if( widgetCombobox ) {
+
 
return oouiSelectors[type].getValue();
+
// Helper function to dedupe a sorted list
} else {
+
function dedupe( arr, fn ) {
return oouiSelectors[type].getMenu().findSelectedItem() ? oouiSelectors[type].getMenu().findSelectedItem().getData() : '';
+
if( !fn ) {
 +
return arr.filter( function( x, i, a ) {
 +
return !i || fn( x ) !== fn( a[i-1] );
 +
} );
 
}
 
}
+
return arr.filter( function( x, i, a ) {
 +
return !i || x !== a[i-1];
 +
} );
 
}
 
}
  
function updateSelector( type ) {
+
// Returns the list of items of a given type for a restricted list of Qids
 +
function getListSelectorFromQids( type, qids ) {
 +
const indexes = qids.map( function( x ) {
 +
return mapping[type][x];
 +
} ).sort();
 +
return indexes.map( function( x ) {
 +
return list[type][x];
 +
} );
 +
}
 +
 
 +
// Initialise a selector and keep the list in memory the result for later reuse
 +
function initSelector( type ) {
 
return function( values ) {
 
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';
+
const widgetType = type === 'speaker' || type === 'language' ? 'ComboBoxInputWidget' : 'DropdownWidget';
var v = values.results.bindings;
+
const v = values.results.bindings;
console.log( type );
+
 
console.log( v );
+
// Save the list in a global variable to quickly filter then
console.log( v.length === 1 ? v[0][ type + 'Label' ].value + " (" + v[0][type].value.substr( 31 ) + ")" : null );
+
// We dedupe because the 'speaker' (only) has duplicate (ordered) values
 +
list[type] = dedupe( v, function( x ) { return x[type].value; } );
 +
 
 +
// Save the mapping Qxx → index to update the list from a list of Qxx (see doQuery)
 +
mapping[type] = list[type].reduce( function( o, x, i ) {
 +
o[ x[type].value.substr( 31 ) ] = i;
 +
}, {} );
 +
 
 +
// Create the OOUI selector
 
oouiSelectors[type] = new OO.ui[widgetType]( {
 
oouiSelectors[type] = new OO.ui[widgetType]( {
placeholder: placeholders[userLanguage][type] ? placeholders[userLanguage][type] : placeholders['en'][type],
+
placeholder: messages['placeholder-'+type][userLanguage] ? messages['placeholder'+type][userLanguage] : messages['placeholder'+type]['en'],
disabled: v.length === 1,
 
 
menu: {
 
menu: {
 
filterFromInput: true,
 
filterFromInput: true,
items: v.map( function( x ) {
+
items: list[type].map( function( x ) {
 
return new OO.ui.MenuOptionWidget( {
 
return new OO.ui.MenuOptionWidget( {
data: x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")",
+
data: widget === 'ComboBoxInputWidget' ? x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")" : x[type].value.substr( 31 ),
 
label: x[ type + 'Label' ].value
 
label: x[ type + 'Label' ].value
 
} );
 
} );
Line 104: Line 162:
 
}
 
}
 
} );
 
} );
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(
 
$( htmlElements[type] ).html('').append(
 
oouiSelectors[type].$element
 
oouiSelectors[type].$element
 
);
 
);
 +
 +
// Save the global matrix: speaker x gender x language x proficiency
 +
if( type === 'speaker' ) {
 +
speakersCriteria = v.map( function( x ) {
 +
return [
 +
x.speaker.value.substr( 31 ),
 +
!x.gender || x.gender.type === 'bnode' ? unknown : x.gender.value.substr( 31 ),
 +
!x.language || x.language.type === 'bnode' ? unknown : x.language.value.substr( 31 ),
 +
!x.proficiency || x.proficiency.type === 'bnode' ? unknown : x.proficiency.value.substr( 31 ),
 +
];
 +
} );
 +
}
  
 
//if( widgetType === 'ComboBoxInputWidget' ) {
 
//if( widgetType === 'ComboBoxInputWidget' ) {
Line 122: Line 185:
 
//}
 
//}
  
 +
};
 +
}
 +
 +
// Update the selector with a given list
 +
function updateSelector( type ) {
 +
return function( values ) {
 +
 +
const widgetType = type === 'speaker' || type === 'language' ? 'ComboBoxInputWidget' : 'DropdownWidget';
 +
 +
oouiSelectors[type].setMenu( {
 +
filterFromInput: true,
 +
items: values.map( function( x ) {
 +
return new OO.ui.MenuOptionWidget( {
 +
data: widget === 'ComboBoxInputWidget' ? x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")" : x[type].value.substr( 31 ),
 +
label: x[ type + 'Label' ].value
 +
} );
 +
} )
 +
} );
 +
 +
if( values.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 ) + ")" );
 +
}
 +
}
 
};
 
};
 
}
 
}
Line 132: Line 221:
 
query: sparqlGlobal['speaker']
 
query: sparqlGlobal['speaker']
 
}
 
}
).done( updateSelector( 'speaker' ) );
+
).done( initSelector( 'speaker' ) );
  
 
$.getJSON(
 
$.getJSON(
Line 139: Line 228:
 
query: sparqlGlobal['gender']
 
query: sparqlGlobal['gender']
 
}
 
}
).done( updateSelector( 'gender' ) );
+
).done( initSelector( 'gender' ) );
  
 
$.getJSON(
 
$.getJSON(
Line 146: Line 235:
 
query: sparqlGlobal['language']
 
query: sparqlGlobal['language']
 
}
 
}
).done( updateSelector( 'language' ) );
+
).done( initSelector( 'language' ) );
  
 
$.getJSON(
 
$.getJSON(
Line 153: Line 242:
 
query: sparqlGlobal['proficiency']
 
query: sparqlGlobal['proficiency']
 
}
 
}
).done( updateSelector( 'proficiency' ) );
+
).done( initSelector( 'proficiency' ) );
 
resetSelectors = false;
 
resetSelectors = false;
 
}
 
}
  
 
function reset() {
 
function reset() {
resetSelectors = true;
+
lastRequest = {
initSelectors();
+
speaker: '',
 +
gender: '',
 +
language: '',
 +
proficiency: '',
 +
};
 +
updateSelector( 'speaker' )( list.speaker );
 +
updateSelector( 'gender' )( list.gender );
 +
updateSelector( 'language' )( list.language );
 +
updateSelector( 'proficiency' )( list.proficiency );
 
$( '#audioresults' ).html( '' );
 
$( '#audioresults' ).html( '' );
 
}
 
}
  
 +
function reduceSpeakers( index, value, arr ) {
 +
return arr.filter( function( x ) {
 +
return x[index] === value;
 +
} );
 +
}
 +
 +
// Add button 'Search'
 
$( '#gosearch' ).html('').append(
 
$( '#gosearch' ).html('').append(
 
( new OO.ui.ButtonInputWidget( {
 
( new OO.ui.ButtonInputWidget( {
 
label: messages['gosearch'][userLanguage] ? messages['gosearch'][userLanguage] : messages['gosearch']['en']
 
label: messages['gosearch'][userLanguage] ? messages['gosearch'][userLanguage] : messages['gosearch']['en']
} ) ).on( 'click', startSearch ).$element
+
} ) ).on( 'click', doQuery ).$element
 
);
 
);
  
 +
// Add button 'Reset'
 
$( '#resetsearch' ).html('').append(
 
$( '#resetsearch' ).html('').append(
 
( new OO.ui.ButtonInputWidget( {
 
( new OO.ui.ButtonInputWidget( {
Line 195: Line 300:
 
var audiobox = new AudioBox( data.results.bindings[ i+index*10 ].record.value.substr( 31 ), box );
 
var audiobox = new AudioBox( data.results.bindings[ i+index*10 ].record.value.substr( 31 ), box );
 
$( '#audioresults' ).append( 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 ) {
 
function applyFn( i ) {
Line 214: Line 317:
  
 
// Do SPARQL request from filters
 
// Do SPARQL request from filters
function doQuery( variable ) {
+
function doQuery() {
  
// Do not modify a selector where there is a value
+
request = {
if( variable && getValueWidget( variable ) ) {
+
speaker: getQValue( 'speaker' ),
 +
gender: getQValue( 'gender' ),
 +
language: getQValue( 'language' ),
 +
proficiency: getQValue( 'proficiency' ),
 +
};
 +
if( JSON.stringify( request ) === JSON.stringify( lastRequest ) ) {
 
return;
 
return;
 
}
 
}
  
function getQ( type ) {
+
lastRequest = request;
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' ),
+
console.log( request );
    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
 
// When all fields are empty, do not query
if( !speaker && !gender && !language && !proficiency ) {
+
if( !request.speaker && !request.gender && !request.language && !request.proficiency ) {
 
return;
 
return;
 
}
 
}
  
var query = "SELECT " + ( variable ? 'DISTINCT ?' + variable + ' ?' + variable + 'Label' : "?record" ) + " WHERE { ?record prop:P2 entity:Q2 ; prop:P4 ?language ; prop:P5 ?speaker . ";
+
var potentialSpeakers = speakersCriteria;
if( speaker ) {
+
 
query += "?record prop:P5 " + speaker + " . ";
+
var query = "SELECT ?record WHERE { ?record prop:P2 entity:Q2 ; prop:P4 ?language ; prop:P5 ?speaker . ";
somevalue = true;
+
if( request.language ) {
}
+
query += "?record prop:P4 entity:" + request.language + " . ";
if( gender ) {
+
potentialSpeakers = reduceSpeakers( 2, request.language, potentialSpeakers );
query += "?record prop:P5 [ prop:P8 " + gender + " ] . ";
 
somevalue = true;
 
}
 
if( language ) {
 
query += "?record prop:P4 " + language + " . ";
 
somevalue = true;
 
 
}
 
}
if( proficiency ) {
+
if( request.speaker ) {
query += "?speaker llp:P4 [ llv:P4 ?language ; llq:P16 " + proficiency + " ] . ";
+
query += "?record prop:P5 entity:" + request.speaker + " . ";
somevalue = true;
+
potentialSpeakers = reduceSpeakers( 0, request.speaker, potentialSpeakers );
}
 
query += "SERVICE wikibase:label { bd:serviceParam wikibase:language '" + userLanguage + ",en,fr' } } LIMIT 100";
 
 
 
if( variable ) {
 
if( !somevalue ) {
 
query = sparqlGlobal[variable];
 
}
 
 
} else {
 
} else {
if( !variable && !somevalue ) {
+
if( request.gender ) {
return;
+
potentialSpeakers = reduceSpeakers( 1, request.gender, potentialSpeakers );
 +
)
 +
if( request.proficiency ) {
 +
potentialSpeakers = reduceSpeakers( 3, request.proficiency, potentialSpeakers );
 
}
 
}
// Voir https://commons.wikimedia.org/wiki/Category:Throbbers - il faut que le fond soit transparent
+
var listSpeakers = dedupe( potentialSpeakers.map( function( x ) {
$( '#audioresults' ).html( '' ).append( '<img src="https://upload.wikimedia.org/wikipedia/commons/7/7a/Balls.gif" width="50" />' );
+
return 'entity:' + x[0];
 +
} ) ).join();
 +
query += 'FILTER( ?speaker IN (' + listSpeakers + ')';
 
}
 
}
 +
query += "} LIMIT 100";
 +
 +
// 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
 
// Execute the request
Line 300: Line 374:
 
);
 
);
  
// Depending if we want the whole results or update on selector
+
// Update the selectors with the restricted values
if( variable ) {
+
// This could have been done a bit earlier, but we launched the SPARQL request before
result.then( updateSelector( variable ), displayError );
+
if( request.speaker ) {
} else {
+
updateSelector( 'speaker' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[0]; } ) ) );
result.then( createAudioBoxesForSearch, displayError );
+
}
 +
if( request.gender ) {
 +
updateSelector( 'gender' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[1]; } ) ) );
 +
}
 +
if( request.language ) {
 +
updateSelector( 'language' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[2]; } ) ) );
 +
}
 +
if( request.proficiency ) {
 +
updateSelector( 'proficiency' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[3]; } ) ) );
 
}
 
}
}
 
  
function startSearch() {
+
result.then( createAudioBoxesForSearch, displayError );
console.log( 'startSearch');
 
if( resetSelectors ) { return; }
 
doQuery();
 
doQuery( 'speaker' );
 
doQuery( 'gender' );
 
doQuery( 'language' );
 
doQuery( 'proficiency' );
 
 
}
 
}
  

Revision as of 18:46, 10 September 2021

// Development in final phase of the interface for displaying contributions
$( function (){
	if( mw.config.get( 'wgPageName' ) !== 'User:Nicolas_NALLET' ) {
		return;
	}
	const userLanguage = mw.config.get( 'wgUserLanguage' );
	const messages = {
		'msg-no-results': {
			en: 'No results.',
			de: 'Keine Ergebnisse.',
			fr: 'Pas de résultat.',
			//qqq: 'Message when there are no results.',
		},
		'button-gosearch': {
			en: 'Search',
			de: 'Suchen',
			fr: 'Rechercher',
			//qqq: 'Button where the user clicks to search.',
		},
		'button-resetsearch': {
			en: 'Reset',
			de: 'Löschen',
			fr: 'Effacer',
			//qqq: 'Button where the user clicks to reset the form.',
		},
		'placeholder-speaker': {
			en: '👤 Speaker',
			fr: '👤 Locuteur',
			//qqq: 'Placeholder for the field Speaker.',
		},
		'placeholder-gender': {
			en: '♀️ ♂️ Speaker\'s gender',
			fr: '♀️ ♂️ Genre du locuteur',
			//qqq: 'Placeholder for the field Gender.',
		},
		'placeholder-language': {
			en: '🏳️ Language',
			fr: '🏳️ Langue',
			//qqq: 'Placeholder for the field Language.',
		},
		'placeholder-proficiency': {
			en: '🥇 Level of proficiency',
			fr: '🥇 Niveau de compétence',
			//qqq: 'Placeholder for the field Proficiency.',
		},
	};
	mw.loader.using( ['oojs', 'oojs-ui', 'mediawiki.api', 'ext.recordWizard.wikibase'], function () {

		oouiSelectors = {
			'speaker': null,
			'gender': null,
			'language': null,
			'proficiency': null,
		};
		var sparqlGlobal = {
			'speaker': 'SELECT ?speaker ?speakerLabel ?gender ?language ?proficiency WHERE { ?speaker prop:P2 entity:Q3 . OPTIONAL { ?speaker prop:P8 ?gender } . OPTIONAL { ?speaker llp:P4 ?statement . ?statement llv:P4 ?language . OPTIONAL { ?statement llq:P16 ?proficiency } } . SERVICE wikibase:label { bd:serviceParam wikibase:language "' + userLanguage + ',fr,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',
		};
		const htmlElements = {
			'speaker': '#filteruser',
			'gender': '#filtergender',
			'language': '#filterlanguage',
			'proficiency': '#filterlevelofproficiency',
		};
		const unknown = {};

		let request = {
			'speaker': '',
			'gender': '',
			'language': '',
			'proficiency': '',
		}, lastRequest = {
			'speaker': '',
			'gender': '',
			'language': '',
			'proficiency': '',
		}, speakersCriteria = [];
		const list = {
			'speaker': [],
			'gender': [],
			'language': [],
			'proficiency': [],
		}, mapping = {
			'speaker': [],
			'gender': [],
			'language': [],
			'proficiency': [],
		};
		var resetSelectors = false;

		// Helper function to obtain the Qvalue of some selector
		function getQValue( type ) {
			let rawValue;
			if( type === 'speaker' || type === 'language' ) {
				rawValue = oouiSelectors[type].getValue();
			} else {
				rawValue = oouiSelectors[type].getMenu().findSelectedItem() ? oouiSelectors[type].getMenu().findSelectedItem().getData() : '';
			}
			rawValue = rawValue.trim();
			if( !rawValue ) {
				return '';
			} else if( /^Q[0-9]+$/.test( rawValue ) ) {
				return rawValue;
			} else if( /\((Q[0-9]+)\)$/.test( rawValue ) ) {
				return rawValue.replace( /.*\((Q[0-9]+)\)$/, '$1' );
			} else {
				return '';
			}
		}

		// Helper function to dedupe a sorted list
		function dedupe( arr, fn ) {
			if( !fn ) {
				return arr.filter( function( x, i, a ) {
					return !i || fn( x ) !== fn( a[i-1] );
				} );
			}
			return arr.filter( function( x, i, a ) {
				return !i || x !== a[i-1];
			} );
		}

		// Returns the list of items of a given type for a restricted list of Qids
		function getListSelectorFromQids( type, qids ) {
			const indexes = qids.map( function( x ) {
				return mapping[type][x];
			} ).sort();
			return indexes.map( function( x ) {
				return list[type][x];
			} );
		}

		// Initialise a selector and keep the list in memory the result for later reuse
		function initSelector( type ) {
			return function( values ) {

				const widgetType = type === 'speaker' || type === 'language' ? 'ComboBoxInputWidget' : 'DropdownWidget';
				const v = values.results.bindings;

				// Save the list in a global variable to quickly filter then
				// We dedupe because the 'speaker' (only) has duplicate (ordered) values
				list[type] = dedupe( v, function( x ) { return x[type].value; } );

				// Save the mapping Qxx → index to update the list from a list of Qxx (see doQuery)
				mapping[type] = list[type].reduce( function( o, x, i ) {
					o[ x[type].value.substr( 31 ) ] = i;
				}, {} );

				// Create the OOUI selector
				oouiSelectors[type] = new OO.ui[widgetType]( {
					placeholder: messages['placeholder-'+type][userLanguage] ? messages['placeholder'+type][userLanguage] : messages['placeholder'+type]['en'],
					menu: {
						filterFromInput: true,				
						items: list[type].map( function( x ) {
							return new OO.ui.MenuOptionWidget( {
								data: widget === 'ComboBoxInputWidget' ? x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")" : x[type].value.substr( 31 ),
								label: x[ type + 'Label' ].value
							} );
						} )
					}
				} );

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

				// Save the global matrix: speaker x gender x language x proficiency
				if( type === 'speaker' ) {
					speakersCriteria = v.map( function( x ) {
						return [
							x.speaker.value.substr( 31 ),
							!x.gender || x.gender.type === 'bnode' ? unknown : x.gender.value.substr( 31 ),
							!x.language || x.language.type === 'bnode' ? unknown : x.language.value.substr( 31 ),
							!x.proficiency || x.proficiency.type === 'bnode' ? unknown : x.proficiency.value.substr( 31 ),
						];
					} );
				}

				//if( widgetType === 'ComboBoxInputWidget' ) {
				//	oouiSelectors[type].on( 'change', onChange );
				//} else {
				//	oouiSelectors[type].getMenu().on( 'change', onChange );
				//}

			};
		}

		// Update the selector with a given list
		function updateSelector( type ) {
			return function( values ) {

				const widgetType = type === 'speaker' || type === 'language' ? 'ComboBoxInputWidget' : 'DropdownWidget';

				oouiSelectors[type].setMenu( {
					filterFromInput: true,				
					items: values.map( function( x ) {
						return new OO.ui.MenuOptionWidget( {
							data: widget === 'ComboBoxInputWidget' ? x[ type + 'Label' ].value + " (" + x[type].value.substr( 31 ) + ")" : x[type].value.substr( 31 ),
							label: x[ type + 'Label' ].value
						} );
					} )
				} );

				if( values.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 ) + ")" );
					}
				}
			};
		}

		function initSelectors() {

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

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

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

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

		function reset() {
			lastRequest = {
				speaker: '',
				gender: '',
				language: '',
				proficiency: '',
			};
			updateSelector( 'speaker' )( list.speaker );
			updateSelector( 'gender' )( list.gender );
			updateSelector( 'language' )( list.language );
			updateSelector( 'proficiency' )( list.proficiency );
			$( '#audioresults' ).html( '' );
		}

		function reduceSpeakers( index, value, arr ) {
			return arr.filter( function( x ) {
				return x[index] === value;
			} );
		}

		// Add button 'Search'
		$( '#gosearch' ).html('').append(
			( new OO.ui.ButtonInputWidget( {
				label: messages['gosearch'][userLanguage] ? messages['gosearch'][userLanguage] : messages['gosearch']['en']
			} ) ).on( 'click', doQuery ).$element
		);

		// Add button 'Reset'
		$( '#resetsearch' ).html('').append(
			( new OO.ui.ButtonInputWidget( {
				label: messages['resetsearch'][userLanguage] ? messages['resetsearch'][userLanguage] : messages['resetsearch']['en']
			} ) ).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 );
				}
				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() {

			request = {
				speaker: getQValue( 'speaker' ),
				gender: getQValue( 'gender' ),
				language: getQValue( 'language' ),
				proficiency: getQValue( 'proficiency' ),
			};
			if( JSON.stringify( request ) === JSON.stringify( lastRequest ) ) {
				return;
			}

			lastRequest = request;

			console.log( request );

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

			var potentialSpeakers = speakersCriteria;

			var query = "SELECT ?record WHERE { ?record prop:P2 entity:Q2 ; prop:P4 ?language ; prop:P5 ?speaker . ";
			if( request.language ) {
				query += "?record prop:P4 entity:" + request.language + " . ";
				potentialSpeakers = reduceSpeakers( 2, request.language, potentialSpeakers );
			}
			if( request.speaker ) {
				query += "?record prop:P5 entity:" + request.speaker + " . ";
				potentialSpeakers = reduceSpeakers( 0, request.speaker, potentialSpeakers );
			} else {
				if( request.gender ) {
					potentialSpeakers = reduceSpeakers( 1, request.gender, potentialSpeakers );
				)
				if( request.proficiency ) {
					potentialSpeakers = reduceSpeakers( 3, request.proficiency, potentialSpeakers );
				}
				var listSpeakers = dedupe( potentialSpeakers.map( function( x ) {
					return 'entity:' + x[0];
				} ) ).join();
				query += 'FILTER( ?speaker IN (' + listSpeakers + ')';
			}
			query += "} LIMIT 100";

			// 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'
				}
			);

			// Update the selectors with the restricted values
			// This could have been done a bit earlier, but we launched the SPARQL request before
			if( request.speaker ) {
				updateSelector( 'speaker' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[0]; } ) ) );
			}
			if( request.gender ) {
				updateSelector( 'gender' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[1]; } ) ) );
			}
			if( request.language ) {
				updateSelector( 'language' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[2]; } ) ) );
			}
			if( request.proficiency ) {
				updateSelector( 'proficiency' )( getListSelectorFromQids( potentialSpeakers.map( function( x ) { return x[3]; } ) ) );
			}

			result.then( createAudioBoxesForSearch, displayError );
		}

		initSelectors();

	} );

} );