2024-05-22 03:48:09 +00:00
|
|
|
/**
|
|
|
|
* Represents a search history object that stores search queries and provides methods to manipulate the history.
|
|
|
|
*
|
|
|
|
* @param {Object} config - The configuration object containing the maximum number of search results allowed.
|
|
|
|
* @return {Object} An object with methods to get, set, add, clear, and initialize the search history.
|
|
|
|
*/
|
2023-08-04 23:49:02 +00:00
|
|
|
function searchHistory( config ) {
|
|
|
|
return {
|
|
|
|
data: [],
|
|
|
|
limit: config.wgCitizenMaxSearchResults,
|
2024-05-22 03:48:09 +00:00
|
|
|
isValidSearchHistory: function ( arr ) {
|
|
|
|
return Array.isArray( arr ) && arr.length <= this.limit;
|
|
|
|
},
|
2023-08-04 23:49:02 +00:00
|
|
|
get: function () {
|
2024-05-22 03:48:09 +00:00
|
|
|
if ( this.data.length === 0 ) {
|
|
|
|
this.init();
|
|
|
|
}
|
2023-08-04 23:49:02 +00:00
|
|
|
return this.data;
|
|
|
|
},
|
2023-08-24 00:44:01 +00:00
|
|
|
set: function ( arr ) {
|
2024-05-22 03:48:09 +00:00
|
|
|
if ( arr && this.isValidSearchHistory( arr ) ) {
|
|
|
|
this.data = arr;
|
|
|
|
mw.storage.set( 'skin-citizen-search-history', JSON.stringify( this.data ) );
|
|
|
|
}
|
2023-08-24 00:44:01 +00:00
|
|
|
},
|
2023-08-04 23:49:02 +00:00
|
|
|
add: function ( query ) {
|
|
|
|
if ( typeof query === 'string' ) {
|
2024-05-22 03:48:09 +00:00
|
|
|
let history = [ ...this.data ];
|
2023-08-04 23:49:02 +00:00
|
|
|
history.unshift( query );
|
2024-05-22 03:48:09 +00:00
|
|
|
history = [ ...new Set( history ) ]; // Remove duplicates
|
2023-08-04 23:49:02 +00:00
|
|
|
if ( history.length > this.limit ) {
|
2024-05-22 03:48:09 +00:00
|
|
|
history.length = this.limit;
|
2023-08-04 23:49:02 +00:00
|
|
|
}
|
2023-08-24 00:44:01 +00:00
|
|
|
this.set( history );
|
2023-08-04 23:49:02 +00:00
|
|
|
}
|
|
|
|
},
|
2024-05-22 03:48:09 +00:00
|
|
|
clear: function () {
|
|
|
|
this.set( [] );
|
|
|
|
mw.storage.remove( 'skin-citizen-search-history' );
|
|
|
|
},
|
2023-08-04 23:49:02 +00:00
|
|
|
init: function () {
|
|
|
|
const storedData = mw.storage.get( 'skin-citizen-search-history' );
|
2023-08-24 00:44:01 +00:00
|
|
|
if ( storedData ) {
|
2024-05-22 03:48:09 +00:00
|
|
|
try {
|
|
|
|
this.data = JSON.parse( storedData );
|
|
|
|
} catch ( error ) {
|
|
|
|
mw.log.error( `[Citizen] Error parsing search history. Stored data: ${ storedData }`, error );
|
|
|
|
}
|
2023-08-24 00:44:01 +00:00
|
|
|
}
|
2023-08-04 23:49:02 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @module searchHistory */
|
|
|
|
module.exports = searchHistory;
|