search: Split out the description highlighter into its own class

No functional change yet, only preparation to allow adding a unit test
later on.

Part-of: <https://gitlab.gnome.org/GNOME/gnome-shell/-/merge_requests/2033>
This commit is contained in:
Sebastian Keller 2021-11-16 18:57:26 +01:00 committed by Marge Bot
parent 9069183cec
commit 5e0c842429
2 changed files with 41 additions and 8 deletions

View File

@ -2,7 +2,7 @@
/* exported findUrls, spawn, spawnCommandLine, spawnApp, trySpawnCommandLine,
formatTime, formatTimeSpan, createTimeLabel, insertSorted,
ensureActorVisibleInScrollView, wiggle, lerp, GNOMEversionCompare,
DBusSenderChecker */
DBusSenderChecker, Highlighter */
const { Clutter, Gio, GLib, Shell, St, GnomeDesktop } = imports.gi;
const Gettext = imports.gettext;
@ -555,3 +555,38 @@ var DBusSenderChecker = class {
this._watchList = [];
}
};
/* @class Highlighter Highlight given terms in text using markup. */
var Highlighter = class {
/**
* @param {?string[]} terms - list of terms to highlight
*/
constructor(terms) {
if (!terms)
return;
const escapedTerms = terms
.map(term => Shell.util_regex_escape(term))
.filter(term => term.length > 0);
if (escapedTerms.length === 0)
return;
this._highlightRegex = new RegExp('(%s)'.format(
escapedTerms.join('|')), 'gi');
}
/**
* Highlight all occurences of the terms defined for this
* highlighter in the provided text using markup.
*
* @param {string} text - text to highlight the defined terms in
* @returns {string}
*/
highlight(text) {
if (!this._highlightRegex)
return text;
return text.replace(this._highlightRegex, '<b>$1</b>');
}
};

View File

@ -10,6 +10,8 @@ const ParentalControlsManager = imports.misc.parentalControlsManager;
const RemoteSearch = imports.ui.remoteSearch;
const Util = imports.misc.util;
const { Highlighter } = imports.misc.util;
const SEARCH_PROVIDERS_SCHEMA = 'org.gnome.desktop.search-providers';
var MAX_LIST_SEARCH_RESULTS_ROWS = 5;
@ -596,7 +598,7 @@ var SearchResultsView = GObject.registerClass({
this._providers = [];
this._highlightRegex = null;
this._highlighter = new Highlighter();
this._searchSettings = new Gio.Settings({ schema_id: SEARCH_PROVIDERS_SCHEMA });
this._searchSettings.connect('changed::disabled', this._reloadRemoteProviders.bind(this));
@ -739,8 +741,7 @@ var SearchResultsView = GObject.registerClass({
if (this._searchTimeoutId == 0)
this._searchTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 150, this._onSearchTimeout.bind(this));
let escapedTerms = this._terms.map(term => Shell.util_regex_escape(term));
this._highlightRegex = new RegExp('(%s)'.format(escapedTerms.join('|')), 'gi');
this._highlighter = new Highlighter(this._terms);
this.emit('terms-changed');
}
@ -894,10 +895,7 @@ var SearchResultsView = GObject.registerClass({
if (!description)
return '';
if (!this._highlightRegex)
return description;
return description.replace(this._highlightRegex, '<b>$1</b>');
return this._highlighter.highlight(description);
}
});