Merge pull request #89 from matrix-org/kegan/slash-command-tab-complete

Implement tab-complete for slash commands
pull/21833/head
Kegsay 2016-01-14 17:34:20 +00:00
commit b491447702
6 changed files with 150 additions and 61 deletions

View File

@ -20,6 +20,31 @@ var dis = require("./dispatcher");
var encryption = require("./encryption"); var encryption = require("./encryption");
var Tinter = require("./Tinter"); var Tinter = require("./Tinter");
class Command {
constructor(name, paramArgs, runFn) {
this.name = name;
this.paramArgs = paramArgs;
this.runFn = runFn;
}
getCommand() {
return "/" + this.name;
}
getCommandWithArgs() {
return this.getCommand() + " " + this.paramArgs;
}
run(roomId, args) {
return this.runFn.bind(this)(roomId, args);
}
getUsage() {
return "Usage: " + this.getCommandWithArgs()
}
}
var reject = function(msg) { var reject = function(msg) {
return { return {
error: msg error: msg
@ -34,18 +59,17 @@ var success = function(promise) {
var commands = { var commands = {
// Change your nickname // Change your nickname
nick: function(room_id, args) { nick: new Command("nick", "<display_name>", function(room_id, args) {
if (args) { if (args) {
return success( return success(
MatrixClientPeg.get().setDisplayName(args) MatrixClientPeg.get().setDisplayName(args)
); );
} }
return reject("Usage: /nick <display_name>"); return reject(this.getUsage());
}, }),
// Changes the colorscheme of your current room // Changes the colorscheme of your current room
tint: function(room_id, args) { tint: new Command("tint", "<color1> [<color2>]", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))( +(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})))?$/); var matches = args.match(/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))( +(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})))?$/);
if (matches) { if (matches) {
@ -62,10 +86,10 @@ var commands = {
); );
} }
} }
return reject("Usage: /tint <primaryColor> [<secondaryColor>]"); return reject(this.getUsage());
}, }),
encrypt: function(room_id, args) { encrypt: new Command("encrypt", "<on|off>", function(room_id, args) {
if (args == "on") { if (args == "on") {
var client = MatrixClientPeg.get(); var client = MatrixClientPeg.get();
var members = client.getRoom(room_id).currentState.members; var members = client.getRoom(room_id).currentState.members;
@ -81,21 +105,21 @@ var commands = {
); );
} }
return reject("Usage: encrypt <on/off>"); return reject(this.getUsage());
}, }),
// Change the room topic // Change the room topic
topic: function(room_id, args) { topic: new Command("topic", "<topic>", function(room_id, args) {
if (args) { if (args) {
return success( return success(
MatrixClientPeg.get().setRoomTopic(room_id, args) MatrixClientPeg.get().setRoomTopic(room_id, args)
); );
} }
return reject("Usage: /topic <topic>"); return reject(this.getUsage());
}, }),
// Invite a user // Invite a user
invite: function(room_id, args) { invite: new Command("invite", "<userId>", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+)$/); var matches = args.match(/^(\S+)$/);
if (matches) { if (matches) {
@ -104,11 +128,11 @@ var commands = {
); );
} }
} }
return reject("Usage: /invite <userId>"); return reject(this.getUsage());
}, }),
// Join a room // Join a room
join: function(room_id, args) { join: new Command("join", "<room_alias>", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+)$/); var matches = args.match(/^(\S+)$/);
if (matches) { if (matches) {
@ -151,17 +175,17 @@ var commands = {
); );
} }
} }
return reject("Usage: /join <room_alias>"); return reject(this.getUsage());
}, }),
part: function(room_id, args) { part: new Command("part", "[#alias:domain]", function(room_id, args) {
var targetRoomId; var targetRoomId;
if (args) { if (args) {
var matches = args.match(/^(\S+)$/); var matches = args.match(/^(\S+)$/);
if (matches) { if (matches) {
var room_alias = matches[1]; var room_alias = matches[1];
if (room_alias[0] !== '#') { if (room_alias[0] !== '#') {
return reject("Usage: /part [#alias:domain]"); return reject(this.getUsage());
} }
if (!room_alias.match(/:/)) { if (!room_alias.match(/:/)) {
var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, ''); var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, '');
@ -198,10 +222,10 @@ var commands = {
dis.dispatch({action: 'view_next_room'}); dis.dispatch({action: 'view_next_room'});
}) })
); );
}, }),
// Kick a user from the room with an optional reason // Kick a user from the room with an optional reason
kick: function(room_id, args) { kick: new Command("kick", "<userId> [<reason>]", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+?)( +(.*))?$/); var matches = args.match(/^(\S+?)( +(.*))?$/);
if (matches) { if (matches) {
@ -210,11 +234,11 @@ var commands = {
); );
} }
} }
return reject("Usage: /kick <userId> [<reason>]"); return reject(this.getUsage());
}, }),
// Ban a user from the room with an optional reason // Ban a user from the room with an optional reason
ban: function(room_id, args) { ban: new Command("ban", "<userId> [<reason>]", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+?)( +(.*))?$/); var matches = args.match(/^(\S+?)( +(.*))?$/);
if (matches) { if (matches) {
@ -223,11 +247,11 @@ var commands = {
); );
} }
} }
return reject("Usage: /ban <userId> [<reason>]"); return reject(this.getUsage());
}, }),
// Unban a user from the room // Unban a user from the room
unban: function(room_id, args) { unban: new Command("unban", "<userId>", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+)$/); var matches = args.match(/^(\S+)$/);
if (matches) { if (matches) {
@ -237,11 +261,11 @@ var commands = {
); );
} }
} }
return reject("Usage: /unban <userId>"); return reject(this.getUsage());
}, }),
// Define the power level of a user // Define the power level of a user
op: function(room_id, args) { op: new Command("op", "<userId> [<power level>]", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+?)( +(\d+))?$/); var matches = args.match(/^(\S+?)( +(\d+))?$/);
var powerLevel = 50; // default power level for op var powerLevel = 50; // default power level for op
@ -266,11 +290,11 @@ var commands = {
} }
} }
} }
return reject("Usage: /op <userId> [<power level>]"); return reject(this.getUsage());
}, }),
// Reset the power level of a user // Reset the power level of a user
deop: function(room_id, args) { deop: new Command("deop", "<userId>", function(room_id, args) {
if (args) { if (args) {
var matches = args.match(/^(\S+)$/); var matches = args.match(/^(\S+)$/);
if (matches) { if (matches) {
@ -289,12 +313,14 @@ var commands = {
); );
} }
} }
return reject("Usage: /deop <userId>"); return reject(this.getUsage());
} })
}; };
// helpful aliases // helpful aliases
commands.j = commands.join; var aliases = {
j: "join"
}
module.exports = { module.exports = {
/** /**
@ -314,13 +340,26 @@ module.exports = {
var cmd = bits[1].substring(1).toLowerCase(); var cmd = bits[1].substring(1).toLowerCase();
var args = bits[3]; var args = bits[3];
if (cmd === "me") return null; if (cmd === "me") return null;
if (aliases[cmd]) {
cmd = aliases[cmd];
}
if (commands[cmd]) { if (commands[cmd]) {
return commands[cmd](roomId, args); return commands[cmd].run(roomId, args);
} }
else { else {
return reject("Unrecognised command: " + input); return reject("Unrecognised command: " + input);
} }
} }
return null; // not a command return null; // not a command
},
getCommandList: function() {
// Return all the commands plus /me which isn't handled like normal commands
var cmds = Object.keys(commands).sort().map(function(cmdKey) {
return commands[cmdKey];
})
cmds.push(new Command("me", "<action>", function(){}));
return cmds;
} }
}; };

View File

@ -32,8 +32,6 @@ const MATCH_REGEX = /(^|\s)(\S+)$/;
class TabComplete { class TabComplete {
constructor(opts) { constructor(opts) {
opts.startingWordSuffix = opts.startingWordSuffix || "";
opts.wordSuffix = opts.wordSuffix || "";
opts.allowLooping = opts.allowLooping || false; opts.allowLooping = opts.allowLooping || false;
opts.autoEnterTabComplete = opts.autoEnterTabComplete || false; opts.autoEnterTabComplete = opts.autoEnterTabComplete || false;
opts.onClickCompletes = opts.onClickCompletes || false; opts.onClickCompletes = opts.onClickCompletes || false;
@ -58,7 +56,7 @@ class TabComplete {
// assign onClick listeners for each entry to complete the text // assign onClick listeners for each entry to complete the text
this.list.forEach((l) => { this.list.forEach((l) => {
l.onClick = () => { l.onClick = () => {
this.completeTo(l.getText()); this.completeTo(l);
} }
}); });
} }
@ -93,10 +91,12 @@ class TabComplete {
/** /**
* Do an auto-complete with the given word. This terminates the tab-complete. * Do an auto-complete with the given word. This terminates the tab-complete.
* @param {string} someVal * @param {Entry} entry The tab-complete entry to complete to.
*/ */
completeTo(someVal) { completeTo(entry) {
this.textArea.value = this._replaceWith(someVal, true); this.textArea.value = this._replaceWith(
entry.getFillText(), true, entry.getSuffix(this.isFirstWord)
);
this.stopTabCompleting(); this.stopTabCompleting();
// keep focus on the text area // keep focus on the text area
this.textArea.focus(); this.textArea.focus();
@ -222,8 +222,9 @@ class TabComplete {
if (!this.inPassiveMode) { if (!this.inPassiveMode) {
// set textarea to this new value // set textarea to this new value
this.textArea.value = this._replaceWith( this.textArea.value = this._replaceWith(
this.matchedList[this.currentIndex].text, this.matchedList[this.currentIndex].getFillText(),
this.currentIndex !== 0 // don't suffix the original text! this.currentIndex !== 0, // don't suffix the original text!
this.matchedList[this.currentIndex].getSuffix(this.isFirstWord)
); );
} }
@ -243,7 +244,7 @@ class TabComplete {
} }
} }
_replaceWith(newVal, includeSuffix) { _replaceWith(newVal, includeSuffix, suffix) {
// The regex to replace the input matches a character of whitespace AND // The regex to replace the input matches a character of whitespace AND
// the partial word. If we just use string.replace() with the regex it will // the partial word. If we just use string.replace() with the regex it will
// replace the partial word AND the character of whitespace. We want to // replace the partial word AND the character of whitespace. We want to
@ -258,13 +259,12 @@ class TabComplete {
boundaryChar = ""; boundaryChar = "";
} }
var replacementText = ( suffix = suffix || "";
boundaryChar + newVal + ( if (!includeSuffix) {
includeSuffix ? suffix = "";
(this.isFirstWord ? this.opts.startingWordSuffix : this.opts.wordSuffix) : }
""
) var replacementText = boundaryChar + newVal + suffix;
);
return this.originalText.replace(MATCH_REGEX, function() { return this.originalText.replace(MATCH_REGEX, function() {
return replacementText; // function form to avoid `$` special-casing return replacementText; // function form to avoid `$` special-casing
}); });

View File

@ -28,6 +28,14 @@ class Entry {
return this.text; return this.text;
} }
/**
* @return {string} The text to insert into the input box. Most of the time
* this is the same as getText().
*/
getFillText() {
return this.text;
}
/** /**
* @return {ReactClass} Raw JSX * @return {ReactClass} Raw JSX
*/ */
@ -42,6 +50,14 @@ class Entry {
return null; return null;
} }
/**
* @return {?string} The suffix to append to the tab-complete, or null to
* not do this.
*/
getSuffix(isFirstWord) {
return null;
}
/** /**
* Called when this entry is clicked. * Called when this entry is clicked.
*/ */
@ -50,6 +66,31 @@ class Entry {
} }
} }
class CommandEntry extends Entry {
constructor(cmd, cmdWithArgs) {
super(cmdWithArgs);
this.cmd = cmd;
}
getFillText() {
return this.cmd;
}
getKey() {
return this.getFillText();
}
getSuffix(isFirstWord) {
return " "; // force a space after the command.
}
}
CommandEntry.fromCommands = function(commandArray) {
return commandArray.map(function(cmd) {
return new CommandEntry(cmd.getCommand(), cmd.getCommandWithArgs());
});
}
class MemberEntry extends Entry { class MemberEntry extends Entry {
constructor(member) { constructor(member) {
super(member.name || member.userId); super(member.name || member.userId);
@ -66,6 +107,10 @@ class MemberEntry extends Entry {
getKey() { getKey() {
return this.member.userId; return this.member.userId;
} }
getSuffix(isFirstWord) {
return isFirstWord ? ": " : " ";
}
} }
MemberEntry.fromMemberList = function(members) { MemberEntry.fromMemberList = function(members) {
@ -99,3 +144,4 @@ MemberEntry.fromMemberList = function(members) {
module.exports.Entry = Entry; module.exports.Entry = Entry;
module.exports.MemberEntry = MemberEntry; module.exports.MemberEntry = MemberEntry;
module.exports.CommandEntry = CommandEntry;

View File

@ -35,7 +35,9 @@ var sdk = require('../../index');
var CallHandler = require('../../CallHandler'); var CallHandler = require('../../CallHandler');
var TabComplete = require("../../TabComplete"); var TabComplete = require("../../TabComplete");
var MemberEntry = require("../../TabCompleteEntries").MemberEntry; var MemberEntry = require("../../TabCompleteEntries").MemberEntry;
var CommandEntry = require("../../TabCompleteEntries").CommandEntry;
var Resend = require("../../Resend"); var Resend = require("../../Resend");
var SlashCommands = require("../../SlashCommands");
var dis = require("../../dispatcher"); var dis = require("../../dispatcher");
var Tinter = require("../../Tinter"); var Tinter = require("../../Tinter");
@ -94,8 +96,6 @@ module.exports = React.createClass({
// xchat-style tab complete, add a colon if tab // xchat-style tab complete, add a colon if tab
// completing at the start of the text // completing at the start of the text
this.tabComplete = new TabComplete({ this.tabComplete = new TabComplete({
startingWordSuffix: ": ",
wordSuffix: " ",
allowLooping: false, allowLooping: false,
autoEnterTabComplete: true, autoEnterTabComplete: true,
onClickCompletes: true, onClickCompletes: true,
@ -422,7 +422,9 @@ module.exports = React.createClass({
return; return;
} }
this.tabComplete.setCompletionList( this.tabComplete.setCompletionList(
MemberEntry.fromMemberList(room.getJoinedMembers()) MemberEntry.fromMemberList(room.getJoinedMembers()).concat(
CommandEntry.fromCommands(SlashCommands.getCommandList())
)
); );
}, },

View File

@ -341,7 +341,7 @@ module.exports = React.createClass({
MatrixClientPeg.get().sendTextMessage(this.props.room.roomId, contentText); MatrixClientPeg.get().sendTextMessage(this.props.room.roomId, contentText);
} }
sendMessagePromise.then(function() { sendMessagePromise.done(function() {
dis.dispatch({ dis.dispatch({
action: 'message_sent' action: 'message_sent'
}); });

View File

@ -18,6 +18,7 @@ limitations under the License.
var React = require('react'); var React = require('react');
var MatrixClientPeg = require("../../../MatrixClientPeg"); var MatrixClientPeg = require("../../../MatrixClientPeg");
var CommandEntry = require("../../../TabCompleteEntries").CommandEntry;
module.exports = React.createClass({ module.exports = React.createClass({
displayName: 'TabCompleteBar', displayName: 'TabCompleteBar',
@ -31,8 +32,9 @@ module.exports = React.createClass({
<div className="mx_TabCompleteBar"> <div className="mx_TabCompleteBar">
{this.props.entries.map(function(entry, i) { {this.props.entries.map(function(entry, i) {
return ( return (
<div key={entry.getKey() || i + ""} className="mx_TabCompleteBar_item" <div key={entry.getKey() || i + ""}
onClick={entry.onClick.bind(entry)} > className={ "mx_TabCompleteBar_item " + (entry instanceof CommandEntry ? "mx_TabCompleteBar_command" : "") }
onClick={entry.onClick.bind(entry)} >
{entry.getImageJsx()} {entry.getImageJsx()}
<span className="mx_TabCompleteBar_text"> <span className="mx_TabCompleteBar_text">
{entry.getText()} {entry.getText()}