Most of the time when we are thinking about sending a chat message as text we just think of sending a string. This work fine in most cases but causes issues when we think about formatting or when needing to define special actions like links. This is a proposal for a potential way of treating messages differently.
Let’s say that you wanted to send this block of text as a message.
“Hello World, this is the BEST! Follow me here.”
How would you interpret the bold text? We could break up the string into distinct tokens that represent a small part of the message.
enum MessageType {
Bold,
Link
}
type Text = string;
type Bold { type: MessageType.Bold, value: string }
type Link { type: MessageType.Link, value: string, url: string }
type MessagePart = Text | Bold | Link;
const message: MessagePart[] = [
'Hello',
'World,',
'this',
'is',
'the',
{ type: MessageType.Bold, value: 'BEST!' },
'follow',
'me',
{ type: MessageType.Link, value: 'here.', url: 'https://www.google.com' }
];
"message" represents the string broken up into distinct parsable tokens. An HTML interpreter for the above message could look something like this.
const interpretMessageToHtml = (message: MessagePart[]): string => {
return message.map((part: MessagePart) => {
if('type' in part) {
switch(part.type) {
case MessageType.Bold:
return `<b>${part.value}</b>`;
case MessageType.Link:
return `<a href="${part.url}">${part.value}</a>`;
}
}
return part;
}).join(' ');
}
interpretMessageToHtml([
'Hello',
'World,',
'this',
'is',
'the',
{ type: MessageType.Bold, value: 'BEST.' },
'Follow',
'me',
{ type: MessageType.Link, value: 'here', url: 'https://www.google.com' }
]);
// Hello World this is the <b>BEST</b>. Follow me <a href="https://www.google.com">here</a>