All files / ext.wikilambda.app/store/stores/wikidata lexemes.js

93.88% Statements 476/507
96.11% Branches 99/103
93.75% Functions 30/32
93.88% Lines 476/507

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 19x 19x 19x 19x 19x 19x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 8x 8x 8x 8x 8x 8x 8x 8x 8x 5x 5x 3x 3x 8x 1x 1x 2x 2x 2x 8x 8x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 1x 1x 1x 1x 1x 1x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x                                           126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 7x 7x 7x 7x 7x 68x 68x 4x 4x 64x 64x 64x 68x 68x 13x 13x 13x 13x 13x 51x 51x 51x 7x 7x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 6x 6x 6x 6x 6x 54x 54x 1x 1x 53x 53x 53x 54x 54x 11x 11x 11x 11x 11x 42x 42x 6x 6x 126x 126x 126x 126x 126x 126x 126x 126x 126x 5x 5x 5x 5x 5x 12x 5x 5x 126x 126x 126x 126x 126x 126x 126x 126x 126x 6x 6x 6x 6x 6x 13x 3x 3x 10x 10x 6x 6x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 6x 6x 6x 6x 6x 125x 1x 1x 124x 124x 124x 124x 125x 125x 43x 43x 43x 43x 43x 81x 81x 6x 6x 126x 126x 126x 126x 126x 126x 126x 126x 5x 5x 5x 5x 5x 11x 3x 3x 8x 8x 5x 5x 5x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 6x 6x 3x 3x 3x 3x 3x 3x 3x 126x 126x 126x 126x 126x 126x 126x 126x 126x 1x 1x 1x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x   126x 126x 126x 126x 126x 126x 126x 126x 126x 1x 126x 126x 126x 126x 126x 126x 126x 126x 126x 9x 9x 9x 9x 9x 9x 9x 4x 4x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 4x 4x 4x 4x 5x 5x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 16x 16x 16x 12x 12x 9x 9x 9x 9x 9x 9x 9x 9x 12x 12x 12x 16x 16x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 126x 126x  
/*!
 * WikiLambda Pinia store: Wikidata Lexemes module
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
const Constants = require( '../../../Constants.js' );
const LabelData = require( '../../classes/LabelData.js' );
const { getNestedProperty } = require( '../../../utils/miscUtils.js' );
const {
	isWikidataLexemeId,
	isWikidataLexemeFormId,
	isWikidataLexemeSenseId
} = require( '../../../utils/wikidataUtils.js' );
 
module.exports = {
	state: {
		lexemes: {},
		senses: {},
		scheduledLexemes: [],
		scheduledLexemesPromise: null
	},
 
	getters: {
		/**
		 * Returns the Lexeme object of a given ID,
		 * the fetch Promise if the fetch request is on the fly,
		 * or undefined if it hasn't been requested yet.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeData: function ( state ) {
			/**
			 * @param {string} id
			 * @return {Object|Promise|undefined}
			 */
			const findLexemeData = ( id ) => state.lexemes[ id ];
			return findLexemeData;
		},
 
		/**
		 * Returns a promise that resolves to the Lexeme data given its Id.
		 * If the lexeme is already cached, returns a resolved promise.
		 * If the lexeme is being fetched, returns the existing promise.
		 * If the lexeme hasn't been requested, returns a rejected promise.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeDataAsync: function () {
			/**
			 * @param {string} id
			 * @return {Promise<Object>}
			 */
			const findLexemeDataAsync = ( id ) => {
				const lexemeData = this.getLexemeData( id );
 
				// If lexeme is already cached (not a promise), return resolved promise
				if ( lexemeData && typeof lexemeData.then !== 'function' ) {
					return Promise.resolve( lexemeData );
				}
 
				// If lexeme is being fetched (is a promise), return that promise
				if ( lexemeData && typeof lexemeData.then === 'function' ) {
					return lexemeData;
				}
 
				// If lexeme hasn't been requested, return rejected promise
				return Promise.reject( new Error( `Lexeme ${ id } not found` ) );
			};
			return findLexemeDataAsync;
		},
		/**
		 * Returns the processed senses data for a given lexeme ID,
		 * the processing Promise if the processing is on the fly,
		 * or undefined if it hasn't been requested yet.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeSensesData: function ( state ) {
			/**
			 * @param {string} lexemeId
			 * @return {Array|Promise|undefined}
			 */
			const findLexemeSensesData = ( lexemeId ) => state.senses[ lexemeId ];
			return findLexemeSensesData;
		},
 
		/**
		 * Returns a promise that resolves to the processed senses data for a given lexeme ID.
		 * If the senses are already processed, returns a resolved promise.
		 * If the senses are being processed, returns the existing promise.
		 * If the senses haven't been requested, returns a rejected promise.
		 *
		 * @return {Function}
		 */
		getLexemeSensesDataAsync: function () {
			/**
			 * @param {string} lexemeId
			 * @return {Promise<Array>}
			 */
			const findLexemeSensesDataAsync = ( lexemeId ) => {
				const sensesData = this.getLexemeSensesData( lexemeId );

				// If senses are already processed (not a promise), return resolved promise
				if ( sensesData && typeof sensesData.then !== 'function' ) {
					return Promise.resolve( sensesData );
				}

				// If senses are being processed (is a promise), return that promise
				if ( sensesData && typeof sensesData.then === 'function' ) {
					return sensesData;
				}

				// If senses haven't been requested, return rejected promise
				return Promise.reject( new Error( `Senses for lexeme ${ lexemeId } not found` ) );
			};
			return findLexemeSensesDataAsync;
		},
 
		/**
		 * Returns the Lexeme form object of a given ID,
		 * or undefined if it hasn't been requested yet
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeFormData: function ( state ) {
			/**
			 * @param {string} id
			 * @return {Object|undefined}
			 */
			const findLexemeFormData = ( id ) => {
				const [ lexemeId ] = id.split( '-' );
				const lexemeData = state.lexemes[ lexemeId ];
				return ( lexemeData && lexemeData.forms ) ?
					lexemeData.forms.find( ( item ) => item.id === id ) :
					undefined;
			};
			return findLexemeFormData;
		},
 
		/**
		 * Returns the LabelData object built from the available
		 * lemmas in the data object of the selected Lexeme.
		 * If a Lexeme is selected but it has no lemmas, returns
		 * LabelData object with the Lexeme id as its display label.
		 * If no Lexeme is selected, returns undefined.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeLabelData: function () {
			/**
			 * @param {string} id The lexeme ID
			 * @return {LabelData|undefined} The `LabelData` object containing label, language code, and directionality.
			 */
			const findLexemeLabelData = ( id ) => {
				// If no selected Lexeme, return undefined
				if ( !id ) {
					return undefined;
				}
				// If no lexemeData yet, return Lexeme Id
				// Get best label from lemmas (if any)
				const lexemeData = this.getLexemeData( id );
				const langs = lexemeData ? Object.keys( lexemeData.lemmas || {} ) : {};
				if ( langs.length > 0 ) {
					const lemma = langs.includes( this.getUserLangCode ) ?
						lexemeData.lemmas[ this.getUserLangCode ] :
						lexemeData.lemmas[ langs[ 0 ] ];
					return new LabelData( id, lemma.value, null, lemma.language );
				}
				// Else, return Lexeme Id as label
				return new LabelData( id, id, null );
 
			};
			return findLexemeLabelData;
		},
 
		/**
		 * Returns the LabelData object built from the available
		 * lemmas in the data object of the selected Lexeme.
		 * If a Lexeme is selected but it has no lemmas, returns
		 * LabelData object with the Lexeme id as its display label.
		 * If no Lexeme is selected, returns undefined.
		 *
		 * @return {Function}
		 */
		getLexemeFormLabelData: function () {
			/**
			 * @param {string} id The Lexeme form ID
			 * @return {LabelData|undefined} The `LabelData` object containing label, language code, and directionality.
			 */
			const findLexemeFormLabelData = ( id ) => {
				// If no selected Lexeme, return undefined
				if ( !id ) {
					return undefined;
				}
				// If no lexemeFormData yet, return Lexeme Id
				const lexemeFormData = this.getLexemeFormData( id );
				// Get best label from representations (if any)
				const langs = lexemeFormData ? Object.keys( lexemeFormData.representations || {} ) : {};
				if ( langs.length > 0 ) {
					const rep = langs.includes( this.getUserLangCode ) ?
						lexemeFormData.representations[ this.getUserLangCode ] :
						lexemeFormData.representations[ langs[ 0 ] ];
					return new LabelData( id, rep.value, null, rep.language );
				}
				// Else, return Lexeme Id as label
				return new LabelData( id, id, null );
			};
			return findLexemeFormLabelData;
		},
 
		/**
		 * Returns the URL for a given lexeme ID.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeUrl: function () {
			/**
			 * @param {string} id
			 * @return {string|undefined}
			 */
			const findLexemeUrl = ( id ) => isWikidataLexemeId( id ) ?
				`${ Constants.WIKIDATA_BASE_URL }/wiki/Lexeme:${ id }` :
				undefined;
			return findLexemeUrl;
		},
 
		/**
		 * Returns the URL for a given lexeme form ID.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeFormUrl: function () {
			/**
			 * @param {string} id
			 * @return {string|undefined}
			 */
			const findLexemeFormUrl = ( id ) => {
				if ( !isWikidataLexemeFormId( id ) ) {
					return undefined;
				}
				const [ lexemeId = '', formId = '' ] = id.split( '-' );
				return `${ Constants.WIKIDATA_BASE_URL }/wiki/Lexeme:${ lexemeId }#${ formId }`;
			};
			return findLexemeFormUrl;
		},
 
		/**
		 * Returns the Lexeme sense object of a given ID,
		 * or undefined if it hasn't been requested yet
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLexemeSenseData: function ( state ) {
			/**
			 * @param {string} id
			 * @return {Object|undefined}
			 */
			const findLexemeSenseData = ( id ) => {
				const [ lexemeId ] = id.split( '-' );
				const sensesData = state.senses[ lexemeId ];
				return ( sensesData && Array.isArray( sensesData ) ) ?
					sensesData.find( ( item ) => item.id === id ) :
					undefined;
			};
			return findLexemeSenseData;
		},
 
		/**
		 * Returns the LabelData object built from the available
		 * representations in the data object of the selected Lexeme Sense.
		 * If a Lexeme Sense is selected but it has no representations, returns
		 * LabelData object with the Lexeme Sense id as its display label.
		 * If no Lexeme Sense is selected, returns undefined.
		 *
		 * @return {Function}
		 */
		getLexemeSenseLabelData: function () {
			/**
			 * @param {string} id The Lexeme sense ID
			 * @return {LabelData|undefined} The `LabelData` object containing label, language code, and directionality.
			 */
			const findLexemeSenseLabelData = ( id ) => {
				if ( !id ) {
					return undefined;
				}
				// If no lexemeSenseData yet, return Lexeme Sense Id
				const lexemeSenseData = this.getLexemeSenseData( id );
 
				// Get best label from representations (if any)
				const langs = lexemeSenseData ? Object.keys( lexemeSenseData.glosses || {} ) : {};
				if ( langs.length > 0 ) {
					const rep = langs.includes( this.getUserLangCode ) ?
						lexemeSenseData.glosses[ this.getUserLangCode ] :
						lexemeSenseData.glosses[ langs[ 0 ] ];
					return new LabelData( id, rep.value, null, rep.language );
				}
				// Else, return Lexeme Id as label
				return new LabelData( id, id, null );
			};
			return findLexemeSenseLabelData;
		},
 
		/**
		 * Returns the URL for a given lexeme sense ID.
		 *
		 * @return {Function}
		 */
		getLexemeSenseUrl: function () {
			/**
			 * @param {string} id
			 * @return {string|undefined}
			 */
			const findLexemeSenseUrl = ( id ) => {
				if ( !isWikidataLexemeSenseId( id ) ) {
					return undefined;
				}
				const [ lexemeId = '', senseId = '' ] = id.split( '-' );
				return `${ Constants.WIKIDATA_BASE_URL }/wiki/Lexeme:${ lexemeId }#${ senseId }`;
			};
			return findLexemeSenseUrl;
		}
	},
 
	actions: {
		/**
		 * Stores the lexeme data indexed by its Id
		 *
		 * @param {Object} payload
		 * @param {string} payload.id
		 * @param {Object} payload.data
		 * @return {undefined}
		 */
		setLexemeData: function ( payload ) {
			// If payload.data is a promise, store it directly
			if ( payload.data && typeof payload.data.then === 'function' ) {
				this.lexemes[ payload.id ] = payload.data;
				return;
			}
 
			// Otherwise, unwrap the data to select only subset of Lexeme data; title, forms, senses and lemmas
			const unwrap = ( { title, forms, senses, lemmas } ) => ( { title, forms, senses, lemmas } );
			this.lexemes[ payload.id ] = unwrap( payload.data );
		},
 
		/**
		 * Removes the lexems for the given IDs
		 *
		 * @param {Object} payload
		 * @param {Array<string>} payload.ids - An array of Wikidata Lexeme IDs
		 */
		resetLexemeData: function ( payload ) {
			payload.ids.forEach( ( id ) => delete this.lexemes[ id ] );
			// Also reset the corresponding senses data
			this.resetLexemeSensesData( { lexemeIds: payload.ids } );
		},
 
		/**
		 * Stores the processed senses data for a given lexeme ID
		 *
		 * @param {Object} payload
		 * @param {string} payload.lexemeId
		 * @param {Array|Promise} payload.data
		 * @return {undefined}
		 */
		setLexemeSensesData: function ( payload ) {
			this.senses[ payload.lexemeId ] = payload.data;
		},
 
		/**
		 * Removes the processed senses data for the given lexeme IDs
		 *
		 * @param {Object} payload
		 * @param {Array<string>} payload.lexemeIds - An array of Wikidata Lexeme IDs
		 */
		resetLexemeSensesData: function ( payload ) {
			payload.lexemeIds.forEach( ( lexemeId ) => delete this.senses[ lexemeId ] );
		},
 
		/**
		 * Fetches the fallback labels for a single sense from its associated item.
		 *
		 * @param {Object} sense - The initial lexeme sense object
		 * @return {Promise<Object>} - Promise that resolves to a new sense object
		 */
		fetchLexemeSenseFallbackLabels: function ( sense ) {
			const claims = sense.claims;
			const itemId = getNestedProperty( claims, 'P5137.0.mainsnak.datavalue.value.id' );
 
			// We do nothing if:
			// - there is already a gloss in the user's language for this sense
			// - there is no 'item for this sense' to fetch for this sense
			if ( sense.glosses[ this.getUserLangCode ] || !itemId ) {
				return Promise.resolve( sense );
			}
 
			// First try to get the item data from cache, then fetch if needed
			return this.getItemDataAsync( itemId )
				.catch( () => this.fetchItems( { ids: [ itemId ] } ).then( () => this.getItemDataAsync( itemId ) ) )
				.then( ( itemData ) => {
					// Check if the item has a label in the user's language
					const label = itemData.labels[ this.getUserLangCode ];
					const description = itemData.descriptions[ this.getUserLangCode ];
					// If there is no label, return the original sense
					if ( !label ) {
						return sense;
					}
					// Otherwise, create a new sense object with the fallback label and return it
					const processedSense = Object.assign( {}, sense );
					processedSense.glosses = Object.assign( {}, sense.glosses );
					processedSense.glosses[ this.getUserLangCode ] = {
						value: description ? `${ label.value } - ${ description.value }` : label.value,
						language: label.language
					};
					return processedSense;
				} )
				.catch( () => sense );
		},
 
		/**
		 * Calls Wikidata Action API to fetch Wikidata Lexemes
		 * given their Ids.
		 *
		 * @param {Object} payload
		 * @param {Array<string>} payload.ids - An array of Wikidata Lexeme IDs to fetch.
		 * @return {Promise} - A promise that resolves to the fetched data.
		 */
		fetchLexemes: function ( { ids } ) {
			this.scheduledLexemes = [ ... new Set( [ ...this.scheduledLexemes, ...ids ] ) ];
 
			if ( !this.scheduledLexemesPromise ) {
				this.scheduledLexemesPromise = new Promise( ( resolve, reject ) => {
					setTimeout( () => {
						this.fetchWikidataEntitiesBatched( {
							ids: this.scheduledLexemes,
							getData: this.getLexemeData,
							setData: this.setLexemeData,
							resetData: this.resetLexemeData
						} ).then( resolve, reject );
						this.scheduledLexemes = [];
						this.scheduledLexemesPromise = null;
					}, Constants.WIKIDATA_REQUEST_TIME_WINDOW );
				} );
			}
 
			return this.scheduledLexemesPromise;
		},
 
		/**
		 * Calls Wikidata Action API to fetch Wikidata Lexemes with their senses
		 * and processes sense fallback labels by fetching associated items.
		 * This is specifically for LexemeSense components that need the sense data.
		 *
		 * @param {Object} payload
		 * @param {Array<string>} payload.lexemeIds - An array of Wikidata Lexeme IDs to fetch.
		 * @return {Promise}
		 */
		fetchLexemeSenses: function ( payload ) {
			// Filter out lexemes that already have processed senses
			const lexemeIds = payload.lexemeIds.filter( ( id ) => this.getLexemeSensesData( id ) === undefined );
 
			if ( lexemeIds.length === 0 ) {
				// If list is empty, do nothing
				return Promise.resolve();
			}
			// Wait for the lexeme to be fetched
			// We need to wait for the lexeme to be fetched before fetching the items for each sense
			// because the items are not part of the lexeme data
			// eslint-disable-next-line arrow-body-style
			const sensePromises = lexemeIds.map( ( id ) => {
				return this.getLexemeDataAsync( id )
					.then( () => {
						const lexemeData = this.getLexemeData( id );
						if ( !lexemeData || !lexemeData.senses ) {
							// Store empty array for lexemes with no senses
							this.setLexemeSensesData( { lexemeId: id, data: [] } );
							return;
						}
 
						// Fetch the fallback labels for each sense
						const processedSensePromises = lexemeData.senses.map(
							( sense ) => this.fetchLexemeSenseFallbackLabels( sense ) );
 
						return Promise.all( processedSensePromises ).then( ( processedSenses ) => {
							this.setLexemeSensesData( { lexemeId: id, data: processedSenses } );
						} );
					} )
					.catch( () => {
						// If getting the lexeme data fails, remove the Lexeme Ids from the senses
						this.resetLexemeSensesData( { lexemeIds } );
					} );
			} );
 
			return Promise.all( sensePromises );
		}
	}
};