From f6a76edfdfa7b5ec0f5c1ecedc62ce82dbb56465 Mon Sep 17 00:00:00 2001 From: Aviral Dasgupta Date: Tue, 21 Jun 2016 05:05:23 +0530 Subject: [PATCH] Fuzzy matching in User and Room providers --- src/autocomplete/RoomProvider.js | 17 ++++++++++++++--- src/autocomplete/UserProvider.js | 17 ++++++++++------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/autocomplete/RoomProvider.js b/src/autocomplete/RoomProvider.js index c61541617d..b1232358b5 100644 --- a/src/autocomplete/RoomProvider.js +++ b/src/autocomplete/RoomProvider.js @@ -3,13 +3,16 @@ import Q from 'q'; import MatrixClientPeg from '../MatrixClientPeg'; import Fuse from 'fuse.js'; -const ROOM_REGEX = /(?=#)[^\s]*/g; +const ROOM_REGEX = /(?=#)([^\s]*)/g; let instance = null; export default class RoomProvider extends AutocompleteProvider { constructor() { super(); + this.fuse = new Fuse([], { + keys: ['name', 'roomId', 'aliases'] + }); } getCompletions(query: String) { @@ -18,12 +21,20 @@ export default class RoomProvider extends AutocompleteProvider { const matches = query.match(ROOM_REGEX); const command = matches && matches[0]; if(command) { - completions = client.getRooms().map(room => { + // the only reason we need to do this is because Fuse only matches on properties + this.fuse.set(client.getRooms().filter(room => !!room).map(room => { + return { + name: room.name, + roomId: room.roomId, + aliases: room.getAliases() + }; + })); + completions = this.fuse.search(command).map(room => { return { title: room.name, subtitle: room.roomId }; - }); + }).slice(0, 4);; } return Q.when(completions); } diff --git a/src/autocomplete/UserProvider.js b/src/autocomplete/UserProvider.js index c850cea7d9..51a85adaf1 100644 --- a/src/autocomplete/UserProvider.js +++ b/src/autocomplete/UserProvider.js @@ -1,6 +1,6 @@ import AutocompleteProvider from './AutocompleteProvider'; import Q from 'q'; -import MatrixClientPeg from '../MatrixClientPeg'; +import Fuse from 'fuse.js'; const ROOM_REGEX = /@[^\s]*/g; @@ -10,19 +10,23 @@ export default class UserProvider extends AutocompleteProvider { constructor() { super(); this.users = []; + this.fuse = new Fuse([], { + keys: ['displayName', 'userId'] + }) } getCompletions(query: String) { let completions = []; - const matches = query.match(ROOM_REGEX); - if(!!matches) { - const command = matches[0]; - completions = this.users.map(user => { + let matches = query.match(ROOM_REGEX); + let command = matches && matches[0]; + if(command) { + this.fuse.set(this.users); + completions = this.fuse.search(command).map(user => { return { title: user.displayName || user.userId, description: user.userId }; - }); + }).slice(0, 4); } return Q.when(completions); } @@ -32,7 +36,6 @@ export default class UserProvider extends AutocompleteProvider { } setUserList(users) { - console.log('setUserList'); this.users = users; }