From fa36c81f256a7b357cc64b42129a119d3c98b056 Mon Sep 17 00:00:00 2001 From: Florrie Date: Tue, 16 Jul 2019 12:08:40 -0300 Subject: Separate jump-to-item/search logic from UI code --- playlist-utils.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'playlist-utils.js') diff --git a/playlist-utils.js b/playlist-utils.js index d679ad7..e6d8947 100644 --- a/playlist-utils.js +++ b/playlist-utils.js @@ -574,6 +574,46 @@ function isTrack(obj) { return !!(obj && obj.downloaderArg) } +function searchForItem(grouplike, value, preferredStartIndex = -1) { + if (value.length) { + // We prioritize searching past the index that the user opened the jump + // element from (oldFocusedIndex). This is so that it's more practical + // to do a "repeated" search, wherein the user searches for the same + // value over and over, each time jumping to the next match, until they + // have found the one they're looking for. + + const lower = value.toLowerCase() + const getName = item => (item && item.name) ? item.name.toLowerCase().trim() : '' + + const testStartsWith = item => getName(item).startsWith(lower) + const testIncludes = item => getName(item).includes(lower) + + const searchPastCurrentIndex = test => { + const start = preferredStartIndex + 1 + const match = grouplike.items.slice(start).findIndex(test) + if (match === -1) { + return -1 + } else { + return start + match + } + } + + const allIndexes = [ + searchPastCurrentIndex(testStartsWith), + searchPastCurrentIndex(testIncludes), + grouplike.items.findIndex(testStartsWith), + grouplike.items.findIndex(testIncludes) + ] + + const matchedIndex = allIndexes.find(value => value >= 0) + if (typeof matchedIndex !== 'undefined') { + return grouplike.items[matchedIndex] + } + } + + return null +} + module.exports = { parentSymbol, updatePlaylistFormat, updateGroupFormat, updateTrackFormat, @@ -590,5 +630,6 @@ module.exports = { parsePathString, getTrackIndexInParent, getNameWithoutTrackNumber, + searchForItem, isGroup, isTrack } -- cgit 1.3.0-6-gf8a5