Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit f32eee9

Browse files
committed
Added slashcommands support to edit message composer
Signed-off-by: Jaiwanth <[email protected]>
1 parent 87b87bf commit f32eee9

File tree

2 files changed

+125
-15
lines changed

2 files changed

+125
-15
lines changed

src/components/views/rooms/EditMessageComposer.js

Lines changed: 118 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,26 @@ limitations under the License.
1616
*/
1717
import React from 'react';
1818
import * as sdk from '../../../index';
19-
import {_t} from '../../../languageHandler';
19+
import {_t, _td} from '../../../languageHandler';
2020
import PropTypes from 'prop-types';
2121
import dis from '../../../dispatcher/dispatcher';
2222
import EditorModel from '../../../editor/model';
2323
import {getCaretOffsetAndText} from '../../../editor/dom';
2424
import {htmlSerializeIfNeeded, textSerialize, containsEmote, stripEmoteCommand} from '../../../editor/serialize';
2525
import {findEditableEvent} from '../../../utils/EventUtils';
2626
import {parseEvent} from '../../../editor/deserialize';
27-
import {PartCreator} from '../../../editor/parts';
27+
import {CommandPartCreator} from '../../../editor/parts';
2828
import EditorStateTransfer from '../../../utils/EditorStateTransfer';
2929
import classNames from 'classnames';
3030
import {EventStatus} from 'matrix-js-sdk/src/models/event';
3131
import BasicMessageComposer from "./BasicMessageComposer";
3232
import MatrixClientContext from "../../../contexts/MatrixClientContext";
33+
import {CommandCategories, getCommand} from '../../../SlashCommands';
3334
import {Action} from "../../../dispatcher/actions";
3435
import CountlyAnalytics from "../../../CountlyAnalytics";
3536
import {getKeyBindingsManager, MessageComposerAction} from '../../../KeyBindingsManager';
3637
import {replaceableComponent} from "../../../utils/replaceableComponent";
38+
import Modal from '../../../Modal';
3739

3840
function _isReply(mxEvent) {
3941
const relatesTo = mxEvent.getContent()["m.relates_to"];
@@ -177,6 +179,21 @@ export default class EditMessageComposer extends React.Component {
177179
dis.dispatch({action: "edit_event", event: null});
178180
dis.fire(Action.FocusComposer);
179181
}
182+
_isSlashCommand() {
183+
const parts = this.model.parts;
184+
const firstPart = parts[0];
185+
if (firstPart) {
186+
if (firstPart.type === "command" && firstPart.text.startsWith("/") && !firstPart.text.startsWith("//")) {
187+
return true;
188+
}
189+
190+
if (firstPart.text.startsWith("/") && !firstPart.text.startsWith("//")
191+
&& (firstPart.type === "plain" || firstPart.type === "pill-candidate")) {
192+
return true;
193+
}
194+
}
195+
return false;
196+
}
180197

181198
_isContentModified(newContent) {
182199
// if nothing has changed then bail
@@ -190,19 +207,112 @@ export default class EditMessageComposer extends React.Component {
190207
return true;
191208
}
192209

193-
_sendEdit = () => {
210+
_getSlashCommand() {
211+
const commandText = this.model.parts.reduce((text, part) => {
212+
// use mxid to textify user pills in a command
213+
if (part.type === "user-pill") {
214+
return text + part.resourceId;
215+
}
216+
return text + part.text;
217+
}, "");
218+
const {cmd, args} = getCommand(commandText);
219+
return [cmd, args, commandText];
220+
}
221+
222+
async _runSlashCommand(cmd, args, roomId) {
223+
const result = cmd.run(roomId, args);
224+
let messageContent;
225+
let error = result.error;
226+
if (result.promise) {
227+
try {
228+
if (cmd.category === CommandCategories.messages) {
229+
messageContent = await result.promise;
230+
} else {
231+
await result.promise;
232+
}
233+
} catch (err) {
234+
error = err;
235+
}
236+
}
237+
if (error) {
238+
console.error("Command failure: %s", error);
239+
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
240+
// assume the error is a server error when the command is async
241+
const isServerError = !!result.promise;
242+
const title = isServerError ? _td("Server error") : _td("Command error");
243+
244+
let errText;
245+
if (typeof error === 'string') {
246+
errText = error;
247+
} else if (error.message) {
248+
errText = error.message;
249+
} else {
250+
errText = _t("Server unavailable, overloaded, or something else went wrong.");
251+
}
252+
253+
Modal.createTrackedDialog(title, '', ErrorDialog, {
254+
title: _t(title),
255+
description: errText,
256+
});
257+
} else {
258+
console.log("Command success.");
259+
if (messageContent) return messageContent;
260+
}
261+
}
262+
263+
_sendEdit = async () => {
194264
const startTime = CountlyAnalytics.getTimestamp();
195265
const editedEvent = this.props.editState.getEvent();
196266
const editContent = createEditContent(this.model, editedEvent);
197267
const newContent = editContent["m.new_content"];
268+
let shouldSend = true;
198269

199270
// If content is modified then send an updated event into the room
200271
if (this._isContentModified(newContent)) {
201272
const roomId = editedEvent.getRoomId();
202-
this._cancelPreviousPendingEdit();
203-
const prom = this.context.sendMessage(roomId, editContent);
204-
dis.dispatch({action: "message_sent"});
205-
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, true, false, editContent);
273+
if (!containsEmote(this.model) && this._isSlashCommand()) {
274+
const [cmd, args, commandText] = this._getSlashCommand();
275+
if (cmd) {
276+
if (cmd.category === CommandCategories.messages) {
277+
editContent["m.new_content"] = await this._runSlashCommand(cmd, args, roomId);
278+
} else {
279+
this._runSlashCommand(cmd, args, roomId);
280+
shouldSend = false;
281+
}
282+
} else {
283+
// ask the user if their unknown command should be sent as a message
284+
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
285+
const {finished} = Modal.createTrackedDialog("Unknown command", "", QuestionDialog, {
286+
title: _t("Unknown Command"),
287+
description: <div>
288+
<p>
289+
{ _t("Unrecognised command: %(commandText)s", {commandText}) }
290+
</p>
291+
<p>
292+
{ _t("You can use <code>/help</code> to list available commands. " +
293+
"Did you mean to send this as a message?", {}, {
294+
code: t => <code>{ t }</code>,
295+
}) }
296+
</p>
297+
<p>
298+
{ _t("Hint: Begin your message with <code>//</code> to start it with a slash.", {}, {
299+
code: t => <code>{ t }</code>,
300+
}) }
301+
</p>
302+
</div>,
303+
button: _t('Send as message'),
304+
});
305+
const [sendAnyway] = await finished;
306+
// if !sendAnyway bail to let the user edit the composer and try again
307+
if (!sendAnyway) return;
308+
}
309+
}
310+
if (shouldSend) {
311+
this._cancelPreviousPendingEdit();
312+
const prom = this.context.sendMessage(roomId, editContent);
313+
dis.dispatch({action: "message_sent"});
314+
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, true, false, editContent);
315+
}
206316
}
207317

208318
// close the event editing and focus composer
@@ -240,7 +350,7 @@ export default class EditMessageComposer extends React.Component {
240350
_createEditorModel() {
241351
const {editState} = this.props;
242352
const room = this._getRoom();
243-
const partCreator = new PartCreator(room, this.context);
353+
const partCreator = new CommandPartCreator(room, this.context);
244354
let parts;
245355
if (editState.hasEditorState()) {
246356
// if restoring state from a previous editor,

src/i18n/strings/en_EN.json

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1436,6 +1436,13 @@
14361436
"Someone is using an unknown session": "Someone is using an unknown session",
14371437
"This room is end-to-end encrypted": "This room is end-to-end encrypted",
14381438
"Everyone in this room is verified": "Everyone in this room is verified",
1439+
"Server error": "Server error",
1440+
"Server unavailable, overloaded, or something else went wrong.": "Server unavailable, overloaded, or something else went wrong.",
1441+
"Unknown Command": "Unknown Command",
1442+
"Unrecognised command: %(commandText)s": "Unrecognised command: %(commandText)s",
1443+
"You can use <code>/help</code> to list available commands. Did you mean to send this as a message?": "You can use <code>/help</code> to list available commands. Did you mean to send this as a message?",
1444+
"Hint: Begin your message with <code>//</code> to start it with a slash.": "Hint: Begin your message with <code>//</code> to start it with a slash.",
1445+
"Send as message": "Send as message",
14391446
"Edit message": "Edit message",
14401447
"Mod": "Mod",
14411448
"This event could not be displayed": "This event could not be displayed",
@@ -1622,13 +1629,6 @@
16221629
"This Room": "This Room",
16231630
"All Rooms": "All Rooms",
16241631
"Search…": "Search…",
1625-
"Server error": "Server error",
1626-
"Server unavailable, overloaded, or something else went wrong.": "Server unavailable, overloaded, or something else went wrong.",
1627-
"Unknown Command": "Unknown Command",
1628-
"Unrecognised command: %(commandText)s": "Unrecognised command: %(commandText)s",
1629-
"You can use <code>/help</code> to list available commands. Did you mean to send this as a message?": "You can use <code>/help</code> to list available commands. Did you mean to send this as a message?",
1630-
"Hint: Begin your message with <code>//</code> to start it with a slash.": "Hint: Begin your message with <code>//</code> to start it with a slash.",
1631-
"Send as message": "Send as message",
16321632
"Failed to connect to integration manager": "Failed to connect to integration manager",
16331633
"You don't currently have any stickerpacks enabled": "You don't currently have any stickerpacks enabled",
16341634
"Add some now": "Add some now",

0 commit comments

Comments
 (0)