From 8053d2933aff9c0016274626f7c359e6366d15ce Mon Sep 17 00:00:00 2001 From: Luke Barnard Date: Wed, 2 Aug 2017 09:35:07 +0100 Subject: [PATCH] Order room completions more intuitively by index of the query in displayedAlias and then length of displayedAlias. (So that aliases where the query appears earlier in the string appear first and if the query is in the same index for two aliases, the shorter one appears first). --- src/autocomplete/RoomProvider.js | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/autocomplete/RoomProvider.js b/src/autocomplete/RoomProvider.js index 09d2d79833..44018fc7b8 100644 --- a/src/autocomplete/RoomProvider.js +++ b/src/autocomplete/RoomProvider.js @@ -23,35 +23,51 @@ import FuzzyMatcher from './FuzzyMatcher'; import {PillCompletion} from './Components'; import {getDisplayAliasForRoom} from '../Rooms'; import sdk from '../index'; +import _sortBy from 'lodash/sortBy'; const ROOM_REGEX = /(?=#)(\S*)/g; let instance = null; +function score(query, space) { + const index = space.indexOf(query); + if (index === -1) { + return Infinity; + } else { + return index; + } +} + export default class RoomProvider extends AutocompleteProvider { constructor() { super(ROOM_REGEX); this.matcher = new FuzzyMatcher([], { - keys: ['name', 'roomId', 'aliases'], + keys: ['displayedAlias', 'name', 'roomId'], }); } async getCompletions(query: string, selection: {start: number, end: number}, force = false) { const RoomAvatar = sdk.getComponent('views.avatars.RoomAvatar'); - let client = MatrixClientPeg.get(); + const client = MatrixClientPeg.get(); let completions = []; const {command, range} = this.getCurrentCommand(query, selection, force); if (command) { // the only reason we need to do this is because Fuse only matches on properties - this.matcher.setObjects(client.getRooms().filter(room => !!room && !!getDisplayAliasForRoom(room)).map(room => { + this.matcher.setObjects(client.getRooms().filter( + (room) => !!room && !!getDisplayAliasForRoom(room), + ).map((room) => { return { room: room, name: room.name, - aliases: room.getAliases(), + displayedAlias: getDisplayAliasForRoom(room), }; })); - completions = this.matcher.match(command[0]).map(room => { + completions = this.matcher.match(command[0]); + completions = _sortBy(completions, [ + (c) => score(query, c.displayedAlias), + (c) => c.displayedAlias.length, + ]).map((room) => { const displayAlias = getDisplayAliasForRoom(room.room) || room.roomId; return { completion: displayAlias, @@ -62,7 +78,9 @@ export default class RoomProvider extends AutocompleteProvider { ), range, }; - }).filter(completion => !!completion.completion && completion.completion.length > 0).slice(0, 4); + }) + .filter((completion) => !!completion.completion && completion.completion.length > 0) + .slice(0, 4); } return completions; }