chat: Plumb message object end to end

This will make it possible for future commits to add hooks that allow
plugins to augment chat messages with arbitrary metadata.
This commit is contained in:
Richard Hansen 2021-10-26 00:56:27 -04:00
parent f1f4ed7c58
commit 0f47ca9046
9 changed files with 113 additions and 42 deletions

View file

@ -0,0 +1,50 @@
'use strict';
/**
* Represents a chat message stored in the database and transmitted among users. Plugins can extend
* the object with additional properties.
*
* Supports serialization to JSON.
*/
class ChatMessage {
static fromObject(obj) {
return Object.assign(new ChatMessage(), obj);
}
/**
* @param {?string} [text] - Initial value of the `text` property.
* @param {?string} [userId] - Initial value of the `userId` property.
* @param {?number} [time] - Initial value of the `time` property.
*/
constructor(text = null, userId = null, time = null) {
/**
* The raw text of the user's chat message (before any rendering or processing).
*
* @type {?string}
*/
this.text = text;
/**
* The user's author ID.
*
* @type {?string}
*/
this.userId = userId;
/**
* The message's timestamp, as milliseconds since epoch.
*
* @type {?number}
*/
this.time = time;
/**
* The user's display name.
*
* @type {?string}
*/
this.userName = null;
}
}
module.exports = ChatMessage;

View file

@ -15,6 +15,7 @@
* limitations under the License.
*/
const ChatMessage = require('./ChatMessage');
const padutils = require('./pad_utils').padutils;
const padcookie = require('./pad_cookie').padcookie;
const Tinycon = require('tinycon/tinycon');
@ -102,10 +103,11 @@ exports.chat = (() => {
send() {
const text = $('#chatinput').val();
if (text.replace(/\s+/, '').length === 0) return;
this._pad.collabClient.sendMessage({type: 'CHAT_MESSAGE', text});
this._pad.collabClient.sendMessage({type: 'CHAT_MESSAGE', message: new ChatMessage(text)});
$('#chatinput').val('');
},
async addMessage(msg, increment, isHistoryAdd) {
msg = ChatMessage.fromObject(msg);
// correct the time
msg.time += this._pad.clientTimeOffset;

View file

@ -272,7 +272,7 @@ const getCollabClient = (ace2editor, serverVars, initialUserInfo, options, _pad)
} else if (msg.type === 'CLIENT_MESSAGE') {
callbacks.onClientMessage(msg.payload);
} else if (msg.type === 'CHAT_MESSAGE') {
chat.addMessage(msg, true, false);
chat.addMessage(msg.message, true, false);
} else if (msg.type === 'CHAT_MESSAGES') {
for (let i = msg.messages.length - 1; i >= 0; i--) {
chat.addMessage(msg.messages[i], true, true);